css三栏布局的五种写法,中间自适应,左右宽度固定
文章目录
假设高度已知,请写出三栏布局,其中左右各位300px,中间自适应
1、左右浮动
<div class="left-center-right">
<style>
.left {
float: left;
width: 300px;
background: red;
}
.right {
float: right;
width: 300px;
background: green;
}
.center {
background: yellow;
}
</style>
<div class="left"></div>
<div class="right"></div>
<div class="center">
<h2>这是浮动布局</h2>
</div>
</div>
2、绝对定位
<div class="left-center-right">
<style>
.left-center-right div {
position: absolute;
}
.left {
left: 0;
width: 300px;
background: red;
}
.right {
right: 0;
width: 300px;
background: green;
}
.center {
left: 300px;
right: 300px;
background: yellow;
}
</style>
<div class="left"></div>
<div class="center">
<h2>这是绝对定位</h2>
</div>
<div class="right"></div>
</div>
3、flex布局
<div class="left-center-right">
<style>
.left-center-right {
display: flex;
}
.left {
width: 300px;
background: red;
}
.right {
width: 300px;
background: green;
}
.center {
flex: 1;
background: yellow;
}
</style>
<div class="left"></div>
<div class="center">
<h2>这是flex布局</h2>
</div>
<div class="right"></div>
</div>
4、table布局
<div class="left-center-right">
<style>
.left-center-right {
display: table;
width: 100%;
}
.left-center-right div {
display: table-cell;
}
.left {
width: 300px;
background: red;
}
.right {
width: 300px;
background: green;
}
.center {
background: yellow;
}
</style>
<div class="left"></div>
<div class="center">
<h2>这是table布局</h2>
</div>
<div class="right"></div>
</div>
5、grid布局
<div class="left-center-right">
<style>
.left-center-right {
display: grid;
width: 100%;
grid-template-rows: 100px;
grid-template-columns: 300px auto 300px;
}
.left {
background: red;
}
.right {
background: green;
}
.center {
background: yellow;
}
</style>
<div class="left"></div>
<div class="center">
<h2>这是grid布局</h2>
</div>
<div class="right"></div>
</div>
优缺点:
浮动布局:因为浮动布局是脱离文档流的,在实际使用的过程中得很好的处理浮动(清除浮动),如果处理不好会引发出一些问题,这是它的缺点;优点是兼容性比较好
绝对定位:优点:快捷,不容易出问题;缺点:由于这个是脱离文档流的导致后面的子元素也是脱离文档流的,导致实用性不太好
flex布局:css3新出的布局方式,兼容性比较好,有效的解决以上两个问题
table布局:兼容性好,由于ie8是不兼容flex布局的,这时候可以使用table布局;缺点:历史的诟病以外还有就是这三栏布局只要有一栏超出了指定的高度,其他两栏也会随之变高,在某些场景中这是不适用的
grid布局:可以做很多事情,代码量相对来说会比较少
如果去掉高度已知,哪些就不适用了?
效果图:
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论