HTML结构和基本样式
HTML的结构为最外层一个div,内层两个div分别代表左右两个div。
<div class="wrapper">
<div class="left">左边,宽度固定</div>
<div class="right">右边,宽度自适应</div>
</div>
给最外层div加上边框。左侧div宽度固定为200px。
.wrapper {
border: 1px solid #000;
}
.left {
width: 200px;
height: 200px;
background-color: rgb(97, 143, 204);
}
.right {
height: 300px;
background-color: rgb(165, 103, 207);
}
之后的所有样式都在这个样式的基础上进行修改。
当前页面布局是这个样子的:
第一种:利用浮动
左侧div利用float脱离文档流,为了不遮挡右侧div,使用margin-left
拉开距离。
.wrapper {
border: 1px solid #000;
}
.left {
width: 200px;
height: 200px;
background-color: rgb(97, 143, 204);
float: left;
}
.right {
height: 300px;
background-color: rgb(165, 103, 207);
margin-left: 200px;
}
效果如图:
第二种:利用绝对定位
同样的,绝对定位也可以使元素脱离文档流,然后为右侧div设置margin-left
拉开距离防止遮挡。
要记得为父元素设置position: relative
。
.wrapper {
border: 1px solid #000;
position: relative;
}
.left {
width: 200px;
height: 200px;
background-color: rgb(97, 143, 204);
position: absolute;
}
.right {
height: 300px;
background-color: rgb(165, 103, 207);
margin-left: 200px;
}
第三种:利用浮动+BFC
首先让左侧元素浮动,使其脱离文档流。为了让浮动不影响右侧元素,可以使右侧元素形成一个BFC。最简单的就是为右侧元素设置overflow: hidden
。
.wrapper {
border: 1px solid #000;
}
.left {
width: 200px;
height: 200px;
background-color: rgb(97, 143, 204);
float: left;
}
.right {
height: 300px;
background-color: rgb(165, 103, 207);
overflow: hidden;
}
第四种:利用flex
首先,给父容器设置display: flex
,然后让右侧div自动放大,撑满剩余空间,设置属性flex: 1 1 auto
(也可简写为flex: auto
)。
.wrapper {
border: 1px solid #000;
display: flex;
}
.left {
width: 200px;
height: 200px;
background-color: rgb(97, 143, 204);
}
.right {
height: 300px;
background-color: rgb(165, 103, 207);
flex: 1 1 auto;
}