两栏布局
float + bfc
利用浮动和浮动元素对块级元素不可见(浮动元素会盖住非浮动的块级元素),然后触发被覆盖的块级元素的 bfc,这样可以是右边蓝色的部分不被左边红色部分覆盖,而是刚好衔接。如果不触发 bfc 可以设置右边的的 margin-left=左边的宽度,但是不能实现右边的元素自适应。
<div>
<p></p>
<p></p>
</div>
p {
height: 20px;
margin: 0px; // 去除p标签默认 margin
}
p:nth-child(1) {
background-color: red;
float: left;
width: 300px;
}
p:nth-child(2) {
background-color: blue;
overflow: hidden; // 触发 bfc
}
flex
设置为 flex 之后,子元素都变成 inline-block,给左侧设置固定宽度,flex-grow 默认为 0,右侧设置 flex-grow:1,表示有剩余空间,就全部是它的。
div {
display: flex;
height: 100px;
}
p {
height: 20px;
margin: 0px;
}
p:nth-child(1) {
background-color: cornsilk;
width: 300px;
}
p:nth-child(2) {
background-color: darkorchid;
flex-grow: 1;
}
三栏布局
float + bfc
这里有个 bug,如果使用这种方式,那么我们必须把第二个元素当做浮动在最右边的元素。
div {
height: 100px;
}
p {
height: 20px;
margin: 0px;
}
p:nth-child(1) {
background-color: red;
width: 300px;
float: left;
}
p:nth-child(2) {
background-color: darkturquoise;
float: right;
width: 300px;
}
p:nth-child(3) {
background-color: blue;
overflow: hidden;
}
flex
div {
height: 100px;
display: flex;
}
p {
height: 20px;
margin: 0px;
}
p:nth-child(1) {
background-color: red;
width: 300px;
}
p:nth-child(2) {
background-color: darkturquoise;
flex-grow: 1;
}
p:nth-child(3) {
background-color: blue;
width: 300px;
}