要实现一个左右两栏布局,其中一栏固定宽度,另一栏自适应宽度,可以使用多种CSS技术。以下是几种常见的实现方式:
float
和 margin
<div class="container">
<div class="left">
固定宽度
</div>
<div class="right">
自适应宽度
</div>
</div>
.container {
overflow: hidden; /* 清除浮动 */
}
.left {
width: 200px; /* 固定宽度 */
float: left;
background-color: #f0f0f0;
}
.right {
margin-left: 200px; /* 左边栏的宽度 */
background-color: #e0e0e0;
}
flexbox
<div class="container">
<div class="left">
固定宽度
</div>
<div class="right">
自适应宽度
</div>
</div>
.container {
display: flex;
}
.left {
width: 200px; /* 固定宽度 */
background-color: #f0f0f0;
}
.right {
flex-grow: 1; /* 自适应宽度 */
background-color: #e0e0e0;
}
grid
<div class="container">
<div class="left">
固定宽度
</div>
<div class="right">
自适应宽度
</div>
</div>
.container {
display: grid;
grid-template-columns: 200px 1fr; /* 左边栏固定宽度,右边栏自适应 */
}
.left {
background-color: #f0f0f0;
}
.right {
background-color: #e0e0e0;
}
calc()
和 float
<div class="container">
<div class="left">
固定宽度
</div>
<div class="right">
自适应宽度
</div>
</div>
.container {
overflow: hidden; /* 清除浮动 */
}
.left {
width: 200px; /* 固定宽度 */
float: left;
background-color: #f0f0f0;
}
.right {
width: calc(100% - 200px); /* 自适应宽度 */
float: left;
background-color: #e0e0e0;
}
inline-block
和 calc()
<div class="container">
<div class="left">
固定宽度
</div>
<div class="right">
自适应宽度
</div>
</div>
.container {
font-size: 0; /* 消除 inline-block 元素之间的空白 */
}
.left, .right {
display: inline-block;
vertical-align: top;
font-size: 16px; /* 恢复字体大小 */
}
.left {
width: 200px; /* 固定宽度 */
background-color: #f0f0f0;
}
.right {
width: calc(100% - 200px); /* 自适应宽度 */
background-color: #e0e0e0;
}
position: absolute
<div class="container">
<div class="left">
固定宽度
</div>
<div class="right">
自适应宽度
</div>
</div>
.container {
position: relative;
}
.left {
width: 200px; /* 固定宽度 */
position: absolute;
left: 0;
top: 0;
background-color: #f0f0f0;
}
.right {
margin-left: 200px; /* 左边栏的宽度 */
background-color: #e0e0e0;
}
float
和 margin
:兼容性好,但需要清除浮动。flexbox
:现代布局方式,代码简洁,兼容性较好。grid
:最现代的布局方式,代码简洁,但兼容性稍差。calc()
和 float
:兼容性好,但代码稍显复杂。inline-block
和 calc()
:兼容性好,但需要处理空白问题。position: absolute
:适用于特定场景,但需要处理定位问题。根据项目需求和浏览器兼容性要求,可以选择最适合的方案。