兩側固定 中間自適應
阿新 • • 發佈:2018-11-10
- 使用絕對定位
左右使用絕對定位 由於絕對定位脫離標準流 center會自動在左右的下面 使用margin 留出左右元素的寬度 這樣可以使中間自適應了
div 元素
<div class="boxleft">left</div>
<div class="boxcenter">content</div>
<div class="boxright">right</div>
css 樣式
/*考慮到瀏覽器相容性 最好還是加上這句*/
html,body{ margin: 0px; padding:0; }
.boxleft, .boxright {
position: absolute;
top:0;
width: 200px;
background-color:blue;
}
.boxleft {
left:0;
}
.boxright {
right: 0;
}
.boxcenter {
margin: 0 200px;
background-color: pink;
}
- 使用浮動定位
左右浮動 左右脫離標準流 center 在正常的文件流中 使用margin指定左右邊距
<div class="boxleft">left</div>
<div class="boxright">right</div>
<div class="boxcenter">content</div>
.boxleft { float: left; width: 200px; background-color:blue; } .boxright { float:right; width: 200px; background-color:blue; } .boxcenter { margin: 0 200px; }
該佈局法的好處是受外界影響小,但是不足是 三個元素的順序,center一定要放在最後,這是和絕對定位不一樣的地方,center佔據文件流位置,所以一定要放在最後,左右兩個元素位置沒有關係。當瀏覽器視窗很小的時候,右邊元素會被擠到下一行
- 使用flex佈局
在外圍包裹一層div,設定為display:flex;兩側設為固定的不縮放 寬度中間設定flex:1 。
flex 0 0 200px;可能幾個屬性會問到 分別是 flex-grow放大比例, flex-shrink縮小比例 和 flex-basis專案將佔據固定空間的簡寫
<div class="wrapper">
<div class="boxleft">left</div>
<div class="boxcenter">content</div>
<div class="boxright">right</div>
</div>
.wrapper {
display: flex;
}
.boxleft, .boxright {
flex: 0 0 200px;
background-color:blue;
}
.boxcenter {
flex: 1;
background-color: pink;
}