题目: 假设高度已知,请写出三蓝布局,其中左右栏分别为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布局兼容性不够好。