三栏布局
float布局
浮动的缺点是造成元素脱离文档流,如果处理不好,后边的元素会塌陷,但是浮动的兼容性比较好,并且容易实现,在处理好与周边元素的关系的情况下,浮动还是很好的选择,也是大部分情况下采用的方案。
// html
<div className="box">
<div className="left">left</div>
<div className="right">right</div>
// center必须在最后
<div className="center">center</div>
</div>
// css
.box {
height: 500px;
background: red;
div {
height: 100%;
}
.left {
width: 200px;
float: left;
background: yellow;
}
.right {
width: 200px;
float: right;
background: blue;
}
.center {
background: pink;
}
}
absolute布局
绝对定位呢我们都知道,同浮动一样也是会脱离文档流,而且,绝对定位最致命的就是以后的元素也必须脱离,在不是整个页面都用定位的情况下还是不建议使用这个方案。
<div className="box">
<div className="left">left</div>
<div className="center">center</div>
<div className="right">right</div>
</div>
.box {
position: relative;
height: 500px;
background: red;
div {
height: 100%;
position: absolute;
}
.left {
left: 0;
width: 200px;
background: yellow;
}
.right {
right: 0;
width: 200px;
background: blue;
}
.center {
left: 200px;
right: 200px;
background: pink;
}
}
table布局
利用表格布局,它的兼容性可以说是非常好,老版本的浏览器也能支持。但是表格在有某一块超出设定宽的时候,其他的两块都会随着变化,一直保持着等高的状态,除非设定高度,但是有些情况下我们是不需要等高的。
<div className="box">
<div className="left">left</div>
<div className="center">center</div>
<div className="right">right</div>
</div>
.box {
display: table;
width: 100%;
height: 500px;
background: red;
div {
height: 100%;
display: table-cell;
}
.left {
width: 200px;
background: yellow;
}
.right {
width: 200px;
background: blue;
}
.center {
background: pink;
}
}
grid布局
利用网格布局可以说是目前最简单的方案,仅仅4行代码就完成了这个效果
<div className="box">
<div className="left">left</div>
<div className="center">center</div>
<div className="right">right</div>
</div>
.box {
display: grid;
width: 100%;
height: 500px;
background: red;
grid-template-rows: 100%; // 所有的子元素的高度:百分比|px
grid-template-columns: 200px auto 200px; // 每列的分布
.left {
background: yellow;
}
.right {
background: blue;
}
.center {
background: pink;
}
}
flex布局
flexbox是一个相对来说完美的解决方法,但是兼容性不是太强,毕竟是是css3的新型布局模式,但是flexbox灵活多变可以使用不同尺寸的屏幕布局要求。
<div className="box">
<div className="left">left</div>
<div className="center">center</div>
<div className="right">right</div>
</div>
.box {
display: flex;
width: 100%;
height: 500px;
background: red;
.left {
width: 200px;
background: yellow;
}
.right {
width: 200px;
background: blue;
}
.center {
flex: 1
background: pink;
}
}