題目: 假設高度已知,請寫出三藍布局,其中左右欄分別爲300px,中間自適應。
一個很經典的佈局面試題。一共有4中比較流行的佈局方案。(不使用table)
第一種 Float佈局
<!-- float方法 -->
<section class="layout float">
<style>
.float-left{
float: left;
width: 300px;
background: yellow
}
.float-right{
float: right;
width: 300px;
background: red
}
.antuo-center{
background: blue;
}
</style>
<div class="float-left"></div>
<div class="float-right"></div>
<div class="antuo-center">
<h1>我是浮動方案</h1>
</div>
</section>
第二種 定位佈局
<!-- 定位方法 -->
<section class="layout position">
<style>
.position-left{
position: absolute;
left: 0;
width: 300px;
background: yellow
}
.position-right{
position: absolute;
right: 0;
width: 300px;
background: red
}
.position-center{
position: absolute;
left: 300px;
right: 300px;
background: blue;
}
</style>
<div class="position-left"></div>
<div class="position-right"></div>
<div class="position-center">
<h1>我是定位方案</h1>
</div>
</section>
第三種 Flex佈局
<!-- flex方法 -->
<section class="layout flex">
<style>
.flex{
display: flex;
margin-top: 300px;
}
.flex-left{
width: 300px;
background: yellow
}
.flex-right{
width: 300px;
background: red
}
.flex-center{
flex: 1;
background: blue;
}
</style>
<div class="flex-left"></div>
<div class="flex-center">
<h1>我是flex方案</h1>
</div>
<div class="flex-right"></div>
</section>
第四種 網格佈局
<!-- 網格佈局 -->
<section class="layout grid">
<style media="screen">
.grid{
display: grid;
width: 100%;
grid-template-rows: 200px;
grid-template-columns: 300px auto 300px;
}
.grid-left{
width: 300px;
background: yellow
}
.grid-right{
width: 300px;
background: red
}
.grid-center{
flex: 1;
background: blue;
}
</style>
<div class="grid-left"></div>
<div class="grid-center">
<h1>我是grid方案</h1>
</div>
<div class="grid-right"></div>
</section>
最後我們一起來看看效果
總結
純float的三欄佈局需要將中間的內容放在最後;
絕對定位的三欄佈局:元素對其有點問題
flex佈局最好,基本沒有大的缺點。
grid佈局兼容性不夠好。