左列宽固定,右列自适应
效果如下:
利用float + margin
<style>
.left {
background-color: red;
width: 200px;
height: 500px;
float: left;
}
.right {
background-color: green;
margin-left: 200px; /* 大于或等于左列宽度 */
height: 500px;
}
</style>
<div class="left">左列定宽</div>
<div class="right">右列自适应</div>
利用float + overflow
<style>
.left {
background-color: red;
width: 200px;
height: 500px;
float: left;
}
.right {
background-color: green;
overflow: hidden; /* 触发bfc达到自适应 */
height: 500px;
}
</style>
<div class="left">左列定宽</div>
<div class="right">右列自适应</div>
利用inline-block + calc函数
右侧自适应元素宽度使用calc函数计算
<style>
.left {
background-color: red;
width: 200px;
height: 500px;
display: inline-block;
}
.right {
background-color: green;
height: 500px;
display: inline-block;
width: calc(100% - 200px);
}
</style>
<div class="left">左列定宽</div>
<div class="right">右列自适应</div>
利用绝对定位
<style>
.parent {
position: relative;
}
.left {
width: 200px;
height: 500px;
position: absolute;
left: 0;
top: 0;
background-color: red;
}
.right {
margin-left: 200px; /* 大于或等于左列宽度 */
background-color: green;
height: 500px;
}
</style>
<div class="parent">
<div class="left">左列定宽</div>
<div class="right">右列自适应</div>
</div>
利用table实现
<style>
.parent {
display: table;
width: 100%;
height: 500px;
table-layout: fixed;
}
.left,
.right {
display: table-cell; /*利用单元格自动分配宽度*/
}
.left {
background-color: red;
width: 200px;
}
.right {
background-color: green;
}
</style>
<div class="parent">
<div class="left">左列定宽</div>
<div class="right">右列自适应</div>
</div>
利用flex实现
<style>
.parent {
display: flex;
width: 100%;
height: 500px;
}
.left {
background-color: red;
width: 200px;
}
.right {
flex: 1;
background-color: green;
}
</style>
<div class="parent">
<div class="left">左列定宽</div>
<div class="right">右列自适应</div>
</div>
利用grid实现
<style>
.parent {
display: grid;
width: 100%;
height: 500px;
grid-template-columns: 200px auto; /* auto关键字表示由浏览器自己决定长度 ,auto换成1fr也行, fr是一个相对尺寸单位,表示剩余空间做等分*/
}
.left {
background-color: red;
}
.right {
background-color: green;
}
</style>
<div class="parent">
<div class="left">左列定宽</div>
<div class="right">右列自适应</div>
</div>
左右两侧元素都自适应
利用float + overflow
<style>
.parent {
overflow: hidden;
}
.left {
background-color: red;
height: 500px;
float: left;
}
.right {
background-color: green;
height: 500px;
overflow: hidden; /* 创建BFC */
}
</style>
<div class="parent">
<div class="left">左列不定宽</div>
<div class="right">右列自适应</div>
</div>
利用flex实现
<style>
.parent {
display: flex;
width: 100%;
height: 500px;
}
.left {
background-color: red;
/* 不用设置宽度 */
}
.right {
flex: 1;
background-color: green;
}
</style>
<div class="parent">
<div class="left">左列不定宽</div>
<div class="right">右列自适应</div>
</div>
利用grid实现
<style>
.parent {
display: grid;
width: 100%;
height: 500px;
grid-template-columns: auto 1fr; /* auto关键字表示由浏览器自己决定长度, fr是一个相对尺寸单位,表示剩余空间做等分*/
}
.left {
background-color: red;
}
.right {
background-color: green;
}
</style>
<div class="parent">
<div class="left">左列不定宽</div>
<div class="right">右列自适应</div>
</div>
欢迎查看其他布局系列文章