佈局代碼如下,文章統一使用佈局
<body>
<div class="wrapper">
<div class="left">左側寬度固定</div>
<div class="right">右側寬度自適應</div>
</div>
</body>
方法一、
左側左浮動,右側margin-left
父容器使用
overflow: hidden
意在解決浮動之後高度塌陷的問題。
左側使用左浮動,右側設置margin-left
固定距離即可
效果圖:
wrapper樣式:
.wrapper {
height: 200px;
width: 100%;
background: aliceblue;
overflow: hidden;
}
左側div樣式
及右側div樣式
.left {
width: 200px;
height: 150px;
background: yellowgreen;
float: left;
}
.right {
height: 150px;
background: sienna;
margin-left: 200px;
}
方法二、
float + BFC方法
左側浮動,但是右側盒子通過overflow: auto;形成了BFC,因此右側盒子不會與浮動的元素重疊。
wrapper樣式:
.wrapper {
height: 200px;
width: 100%;
background: aliceblue;
overflow: hidden;
}
左側div樣式
及右側div樣式
.left {
width: 200px;
height: 150px;
background: yellowgreen;
float: left;
}
.right {
height: 150px;
background: sienna;
overflow: auto;
}
效果圖:
方法三、
左側絕對定位,右側margin-left
父容器使用
position: relative
是爲了給子元素一個參照
左側使用position: absolute
,top,left
爲0 是爲了固定位置,右側仍然設置margin-left
固定距離即可
效果圖:
wrapper樣式:
.wrapper {
height: 200px;
width: 100%;
background: aliceblue;
position: relative;
}
左側div樣式
及右側div樣式
.left {
width: 200px;
height: 150px;
background: yellowgreen;
position: absolute;
top: 0;
left: 0;
}
.right {
height: 150px;
background: sienna;
margin-left: 200px;
}
缺點:
- 使用了絕對定位,若是用在某個div中,需要更改父容器的position。
- 沒有清除浮動的方法,若左側盒子高於右側盒子,就會超出父容器的高度。因此只能通過設置父容器的min-height來放置這種情況。
方法四、
flex彈性佈局
父容器設置
display: flex;
讓子div成爲容器方便管理
左側固定寬度,右側自動填充剩餘空間
關於flex屬性,不瞭解的可藉此傳送門 → 彈性佈局 flex
效果圖:
wrapper樣式:
.wrapper {
height: 200px;
width: 100%;
background: aliceblue;
display: flex;
}
左側div樣式
及右側div樣式
.left {
width: 200px;
height: 150px;
background: yellowgreen;
flex: 0 0 200px;
}
.right {
height: 150px;
background: sienna;
flex: 1;
}