实现css三栏布局的五种方式:
首先,需求:实现一个三栏布局,高度均为100px,左侧与右侧宽度为300px,中间自适应。
第一步,重置css,并给统一的高度。:
html *{
padding: 0;
margin: 0;
}
section article div{
min-height: 100px;
}
1.float布局
代码如下:
<section class="float">
<style>
.float-1{
background: aqua;
float: left;
width: 300px;
}
.float-2{
background: red;
}
.float-3{
background: yellow;
float: right;
width: 300px;
}
</style>
<article style="margin-top: 10px">
<div class="float-1">float111</div>
<div class="float-3">float333</div>
<div class="float-2">float222</div>
</article>
</section>
这种方式的优点是兼容性很好,缺点是需要清除浮动,当元素被拉伸时,会出现一些可怕的后果:
此时给中间元素创建bfc
.float-2{
background: red;
overflow: hidden;
}
2.绝对定位:
<section class="absolute" style="margin-top: 20px">
<style>
.absolute-1{
background: aqua;
position: absolute;
left: 0;
width: 300px;
}
.absolute-2{
background: red;
position: absolute;
left: 300px;
right: 300px;
}
.absolute-3{
background: yellow;
position: absolute;
right: 0;
width: 300px;
}
</style>
<article>
<div class="absolute-1">absolute111</div>
<div class="absolute-2">absolute222</div>
<div class="absolute-3">absolute333</div>
</article>
</section>
这种方式的有点是快捷,但是这样元素也是脱离文档流的。
经过拉伸,右侧元素长度固定,向左覆盖
3.flex布局:
<section style="margin-top: 140px">
<style>
.article-flex{
display: flex;
flex-direction: row;
}
.flex-1{
width: 300px;
background: aqua;
}
.flex-2{
flex: 1;
background: red;
}
.flex-3{
width: 300px;
background: yellow;
}
</style>
<article class="article-flex">
<div class="flex-1">flex111</div>
<div class="flex-2">flex222</div>
<div class="flex-3">flex333</div>
</article>
</section>
这是一种比较完美的布局方式,但是兼容性可能对于比较低端的浏览器不支持。
经过拉伸以后,中间的元素会保留足够的空间,左右两边固定宽度的内容会被拉伸。
4.table布局
<section style="margin-top: 20px">
<style>
.table{
display: table;
height: 100px;
width: 100%;
}
.table-1{
display: table-cell;
width: 300px;
background: aqua;
}
.table-2{
display: table-cell;
background: red;
}
.table-3{
display: table-cell;
width: 300px;
background: yellow;
}
</style>
<article class="table">
<div class="table-1">table111</div>
<div class="table-2">table222</div>
<div class="table-3">table333</div>
</article>
</section>
拉伸以后的效果和flex一样:
5.grid布局:
<section style="margin-top: 20px">
<style>
.grid{
display: grid;
height: 100px;
width: 100%;
grid-template-rows: 100px;
grid-template-columns: 300px auto 300px;
}
.grid-1{
display: table-cell;
width: 300px;
background: aqua;
}
.grid-2{
display: table-cell;
background: red;
}
.grid-3{
display: table-cell;
width: 300px;
background: yellow;
}
</style>
<article class="grid">
<div class="grid-1">grid111</div>
<div class="grid-2">grid222</div>
<div class="grid-3">grid333</div>
</article>
</section>
拉伸以后中间部分由于自动所以会被拉伸,其余两个部分会产生滑条