前端面试中一个非常容易问到的基础问题,如何用 CSS 实现两栏布局。
CSS 布局的问题非常基础,每一个合格的前端都肯定学过,但实现的方法有非常多,面试官肯定不满足于一两种方法,你能想到足够多的实现方法吗?
题目:
<div class="wrap">
<div class="left">left</div>
<div class="right">right</div>
</div>
对于以上代码,如何实现左右两栏布局,并且可以自适应屏幕宽度,子元素保持比例缩放?
flex布局
最常见的一种实现方式,父容器设置display: flex;,默认主轴方向为横向,子元素设置flex属性可以实现子元素按比例撑满父容器。
.wrap {
background-color: azure;
display: flex;
}
.left {
background-color: antiquewhite;
flex: 2;
}
.right {
background-color: aquamarine;
flex: 1;
}
grid布局
实现方式和 flex 布局一样简单,设置父容器为display: grid;,并且设置两栏的宽度。
.wrap {
background-color: azure;
display: grid;
grid-template-columns: 50% 50%;
}
.left {
background-color: antiquewhite;
}
.right {
background-color: aquamarine;
}
float
将左子元素设置为 float,并设置宽度,右子元素会自动填补剩余的空间
.wrap {
background-color: azure;
}
.left {
background-color: antiquewhite;
float: left;
width: 50%;
}
.right {
background-color: aquamarine;
}
absolute + margin-left
左子元素设置相对父容器的绝对定位,右子元素设置 margin-left
.wrap {
background-color: azure;
position: relative;
}
.left {
background-color: antiquewhite;
position: absolute;
width: 50%;
}
.right {
background-color: aquamarine;
margin-left: 50%;
}
table 布局
注意 table 布局下,文档流中的父容器默认不会横向撑满,而是子元素的宽高之和,需要设置宽度为百分比。
.wrap {
background-color: azure;
display: table;
width: 100%;
}
.left {
background-color: antiquewhite;
display: table-cell;
width: 50%;
}
.right {
background-color: aquamarine;
display: table-cell;
width: 50%;
}