经典的左右两栏布局,有多少种实现方法?
所谓的左右两栏布局,就是左侧宽度固定,右侧宽度自适应
,下面给大家讲讲实现经典的左右两栏布局,可以有以下这7个方法。
页面上的 DOM 结构如下:
<div class="container">
<div class="left">我是侧边栏</div>
<div class="right">我是内容区域</div>
</div>
方法1:使用 flex 布局(最常用)
实现思路: 左边元素设置固定宽度,右边元素设置CSS属性 flex: 1
。
.container {
display: flex;
width: 100%;
height: 500px;
}
.left {
width: 240px;
height: 100%;
background-color: lightskyblue;
}
.right {
flex: 1;
height: 100%;
background-color: red;
}
方法2:使用 浮动
实现思路: 左边元素设置固定宽度,并设置CSS属性 float: left
,右边元素设置CSS属性 margin-left
,其值等于左边元素的宽度。
.container {
width: 100%;
height: 500px;
}
.left {
float: left;
width: 240px;
height: 100%;
background-color: lightskyblue;
}
.right {
margin-left: 240px;
height: 100%;
background-color: red;
}
方法3:同样使用 浮动
实现思路: 左边元素设置固定宽度,并设置CSS属性 float: left
,右边元素设置CSS属性 overflow: auto
,此时右边就会触发了 BFC
,BFC
的区域不会与设置浮动的元素发生重叠,所以两侧就不会发生重叠。
.container {
width: 100%;
height: 100vh;
}
.left {
float: left;
width: 240px;
height: 100%;
background-color: lightskyblue;
}
.right {
height: 100%;
overflow: auto;
background-color: red;
}
方法4:使用 相对/绝对定位
实现思路: 父级元素设置 position: relative
,左边元素设置固定宽度,并设置CSS属性 position: absolute
,右边元素设置CSS属性 margin-left
,其值等于左边元素的宽度。
.container {
height: 500px;
position: relative;
}
.left {
width: 240px;
height: 100%;
position: absolute;
background-color: lightskyblue;
}
.right {
height: 100%;
margin-left: 240px;
background-color: red;
}
注意:
- absolute 会让元素脱离文档流,right 会直接将内容顶上去,所以我们需要设置 margin-left,其值等于左边元素的宽度。
- div 的宽度默认是 100%,但是当设置了 absolute 之后,宽度不再是 100%,而是由内容的宽度决定的。 解决方法:
- 可以直接设置 width: 100%。
- 也可以设置 left: 0; right: 0。
方法5:同样使用 相对/绝对定位
实现思路: 父级元素设置CSS属性 position: relative
,左边元素设置固定宽度,右边元素设置CSS属性 position: absolute
,并设置 left、right、top、bottom
属性的值,其中 left
的值等于左边元素的宽度。
.container {
height: 500px;
position: relative;
}
.left {
width: 240px;
height: 100%;
background-color: lightskyblue;
}
.right {
height: 100%;
position: absolute;
left: 240px;
right: 0;
top: 0;
bottom: 0;
background-color: red;
}
方法6:使用表格布局 table
实现思路: 父级元素设置CSS属性 display: table
,并设置宽度 100%;左边元素设置CSS属性 display: table-cell
,并设置固定宽度;右边元素设置CSS属性 table-cell
即可。
.container {
display: table;
width: 100%;
height: 500px;
}
.left {
display: table-cell;
width: 240px;
height: 100%;
background-color: lightskyblue;
}
.right {
display: table-cell;
height: 100%;
background-color: red;
}
方法7:使用 calc 函数
实现思路: 左边元素设置CSS属性 float: left
,并设置固定宽度;右边元素设置CSS属性 float: left
并设置宽度 width
,其值等于 calc(100% - 左侧元素的宽度)
。
.container {
width: 100%;
height: 500px;
}
.left {
float: left;
width: 240px;
height: 100%;
background-color: lightskyblue;
}
.right {
float: left;
width: calc(100% - 240px);
height: 100%;
background-color: red;
}
这7个方法的效果图都如下所示。
学会了两栏布局,再去写三栏布局的 CSS,没什么太大的问题!
转载自:https://juejin.cn/post/7085974846458298382