HTML结构
<div class="parent">
<div class="leftBox">左边宽度固定盒子</div>
<div class="rightBox">右边宽度自适应盒子</div>
</div>
相关CSS代码
注:以下CSS为Less写法,读者可转换成原生CSS,除清除浮动代码与本文布局有关,其余样式是为了效果展示,关联不大,读者可忽略。
// 父盒子样式
.parentStyle() {
margin: 20px;
background: bisque;
}
// 左盒子样式
.leftBoxStyle() {
width: 200px;
height: 200px;
background: cyan;
}
// 右盒子样式
.rightBoxStyle() {
background: #1890ff;
}
// 清除浮动
.clearFix() {
&::after {
display: block;
content: "";
clear: both;
}
}
(1)float: left + margin-left:左盒子宽度
.parent {
.parentStyle();
.clearFix(); //清除浮动
.leftBox {
float: left;
.leftBoxStyle();
}
.rightBox {
margin-left: 200px;
.rightBoxStyle();
}
}
(2)绝对定位 + margin-left:左盒子宽度
.parent {
position: relative;
height: 200px;//父盒子定高
.parentStyle();
.leftBox {
position:absolute;
.leftBoxStyle();
}
.rightBox {
margin-left: 200px;
.rightBoxStyle();
}
}
(3)利用table属性
.parent {
display: table;
width: 100%;
.parentStyle();
.leftBox {
display: table-cell;
.leftBoxStyle();
}
.rightBox {
display: table-cell; //如右盒子不需与左盒子等高,可去除这句
.rightBoxStyle();
}
}
(4)float: left + 右盒子width: calc(100% - 左盒子宽)
.parent {
.parentStyle();
.clearFix();
.leftBox {
.leftBoxStyle();
float: left;
}
.rightBox {
.rightBoxStyle();
float: left;
// width: calc(100% - 200px); //css写这句
width: calc(~"100% - 200px");
}
}
(5)display: inline-block; + 右盒子width: calc(100% - 左盒子宽)
.parent {
.parentStyle();
.leftBox {
.leftBoxStyle();
display: inline-block
}
.rightBox {
.rightBoxStyle();
display: inline-block
// width: calc(100% - 200px); //css写这句
width: calc(~"100% - 200px");
}
}
效果如(4)的效果图一样。
(6)overflow: auto
.parent {
.parentStyle();
.clearFix();
// overflow: auto;//也可以
.leftBox {
.leftBoxStyle();
float: left;
}
.rightBox {
.rightBoxStyle();
overflow: auto;
}
}
效果如(4)的效果图一样。
(7)利用flex 左右盒子等高
.parent {
.parentStyle();
display: flex;
.leftBox {
.leftBoxStyle();
}
.rightBox {
.rightBoxStyle();
flex: 1;
}
}
最后:每种方法都有其适用之处,读者可根据需求自行选择。