css實現兩欄佈局,左側固定寬,右側自適應的七種方法
阿新 • • 發佈:2018-12-15
一個面試會問的問題,如何實現兩個盒子,左側固定寬度,右側自適應。
下面是實現的其中方法:
1、利用 calc 計算寬度的方法
css程式碼如下:
.box{overflow: hidden;height: 100px;margin: 10px 0;}
.box>div{height: 100%;}
#box1>div{float: left;}
.left1{width: 100px;background: yellow;}
.right1{background: #09c;width:calc(100% - 100px);}
dom結構如下:
<div class="box" id="box1"> <div class="left1">左側定寬</div> <div class="right1">右側自適應</div> </div>
2、利用 float 配合 margin 實現
css程式碼如下:
.box{overflow: hidden;height: 100px;margin: 10px 0;}
.box>div{height: 100%;}
.left2{float: left;background: yellow;width: 100px;}
.right2{background: #09c;margin-left: 100px;}
dom結構如下:
<div class="box" id="box2"> <div class="left2">左側定寬</div> <div class="right2">右側自適應</div> </div>
3、利用 float 配合 overflow 實現
css程式碼如下:
.box{overflow: hidden;height: 100px;margin: 10px 0;}
.box>div{height: 100%;}
.left3{float: left;background: yellow;width: 100px;}
.right3{background: #09c;overflow: hidden;}
dom結構如下:
<div class="box" id="box3"> <div class="left3">左側定寬</div> <div class="right3">右側自適應</div> </div> // 注意: 如果是左側自適應,右側定寬,下面的寫法中, 右側定寬的內容會被頂下去,所以要交換一下書寫的位置:把定寬的元素放在上面 <div class="box" id="box3"> <div class="left">左側自適應</div> <div class="right">右側定寬</div> </div>
4、利用 position:absolute 配合 margin 實現
css程式碼如下:
.box{overflow: hidden;height: 100px;margin: 10px 0;}
.box>div{height: 100%;}
#box4{position: relative;}
.left4{position: absolute;left: 0;top:0;width: 100px;background: yellow;}
.right4{margin-left:100px;background: #09c;}
dom結構如下:
<div class="box" id="box4">
<div class="left4">左側定寬</div>
<div class="right4">右側自適應</div>
</div>
5、利用 position:absolute 實現
css程式碼如下:
.box{overflow: hidden;height: 100px;margin: 10px 0;}
.box>div{height: 100%;}
#box5{position: relative;}
.left5{position: absolute;left: 0;top:0;width: 100px;background: yellow;}
.right5{position: absolute;left: 100px;top:0;right: 0;
width: 100%;background: #09c;}
dom結構如下:
<div class="box" id="box5">
<div class="left5">左側定寬</div>
<div class="right5">右側自適應</div>
</div>
6、利用 display: flex 實現
css程式碼如下:
.box{overflow: hidden;height: 100px;margin: 10px 0;}
.box>div{height: 100%;}
#box6{display: flex;display: -webkit-flex;}
.left6{flex:0 1 100px;background: yellow;}
.right6{flex:1;background: #09c;}
dom結構如下:
<div class="box" id="box6">
<div class="left6">左側定寬</div>
<div class="right6">右側自適應</div>
</div>
7、利用 display: table 實現
css程式碼如下:
.box{overflow: hidden;height: 100px;margin: 10px 0;}
.box>div{height: 100%;}
#box7{display: table;width: 100%;}
#box7>div{display: table-cell;}
.left7{width: 100px;background: yellow;}
.right7{background: #09c;}
dom結構如下:
<div class="box" id="box7">
<div class="left7">左側定寬</div>
<div class="right7">右側自適應</div>
</div>
實現效果如下圖: