两栏布局,左侧固定,右侧自适应
我总结了以下几种方法
- 左侧固定 + 右侧margin
- 左侧固定 + 父级padding
- 左侧浮动 + 右侧BFC
- 左侧浮动 + 右侧margin
- 先两个在一行 + 右侧calc
- 弹性布局
DOM结构
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
初始样式
<style>
.container {
width: 500px;
height: 300px;
}
.left,
.right {
height: 100%;
}
.left {
width: 200px;
background-color: #0ff;
}
.right {
background-color: #f0f;
}
</style>
两栏布局效果
第一种
左侧固定 + 右侧margin
<style>
.container {
position: relative;
}
.left {
position: absolute;
left : 0;
top : 0;
}
.right {
margin-left: 200px;
}
</style>
第二种
左侧固定 + 父级padding
<style>
.container {
position: relative;
padding-left: 200px;
box-sizing: border-box;
}
.left {
position: absolute;
left : 0;
top : 0;
}
</style>
第三种
左侧浮动 + 右侧BFC
<style>
.left {
float: left;
}
.right {
overflow: auto;
}
</style>
第四种
左侧浮动 + 右侧margin
<style>
.left {
float: left;
}
.right {
margin-left: 200px;
}
</style>
第五种
先两个在一行(浮动或通过设置display也行,也可以flex) + 右侧calc
<style>
.left,.right {
display: inline-block;
}
.right {
width: calc(100% - 200px);
}
</style>
<div class="container">
<div class="left"></div><div class="right"></div>
<!-- 需要考虑空白字符 -->
</div>
<style>
/*如果父元素没有设置高度,需要清除浮动 */
.left,.right {
float: left;
}
.right {
width: calc(100% - 200px);
}
</style>
<style>
.container {
display: flex;
}
.right {
width: calc(100% - 200px);
}
</style>
第六种
<style>
.container {
display: flex;
}
.right {
flex: 1; /* flex : 1 1 0 */
}
</style>
如果有疑问,可以在评论区留言,也欢迎补充。