现有该布局结构
<div class="outer">
<div class="left">左侧</div>
<div class="right">右侧</div>
</div>
1. 利用浮动,左边元素宽度固定 ,设置向左浮动。将右边元素的 margin-left
设为固定宽度 。注意,因为右边元素的 width
默认为 auto
,所以会自动撑满父元素。
.outer {
height: 100px;
}
.left {
background-color: lightblue;
width: 300px;
height: 100px;
float: left;
}
.right {
margin-left: 300px;
height: 100px;
background-color: saddlebrown;
}
2.同样利用浮动,左边元素宽度固定 ,设置向左浮动。右侧元素设置 overflow: hidden;
这样右边就触发了 BFC
,BFC
的区域不会与浮动元素发生重叠,所以两侧就不会发生重叠。
.outer {
height: 100px;
}
.left {
background-color: lightblue;
width: 300px;
height: 100px;
float: left;
}
.right {
height: 100px;
overflow: hidden;
background-color: saddlebrown;
}
3.利用 flex
布局,左边元素固定宽度,右边的元素设置 flex: 1
。
.outer {
height: 100px;
display: flex;
}
.left {
background-color: lightblue;
width: 300px;
height: 100px;
}
.right {
height: 100px;
flex: 1;
background-color: saddlebrown;
}
4. 利用绝对定位,父级元素设为相对定位。左边元素 absolute
定位,宽度固定。右边元素的 margin-left
的值设为左边元素的宽度值。
.outer {
height: 100px;
position:relative;
}
.left {
background-color: lightblue;
width: 300px;
height: 100px;
position: absolute;
}
.right {
height: 100px;
margin-left: 300px;
background-color: saddlebrown;
}
5.利用绝对定位,父级元素设为相对定位。左边元素宽度固定,右边元素 absolute
定位, left
为宽度大小,其余方向定位为 0
。
.outer {
height: 100px;
position: relative;
}
.left {
background-color: lightblue;
width: 300px;
height: 100px;
}
.right {
height: 100px;
background-color: saddlebrown;
position: absolute;
left: 300px;
top: 0;
bottom: 0;
right: 0;
}