一個面試會問的問題,如何實現兩個盒子,左側固定寬度,右側自適應。css
一、利用 calc 計算寬度的方法web
.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);}
<div class="box" id="box1"> <div class="left1">左側定寬</div> <div class="right1">右側自適應</div> </div>
二、利用 float 配合 margin 實現面試
.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;}
<div class="box" id="box2"> <div class="left2">左側定寬</div> <div class="right2">右側自適應</div> </div>
三、利用 float 配合 overflow 實現dom
.box{overflow: hidden;height: 100px;margin: 10px 0;} .box>div{height: 100%;} .left3{float: left;background: yellow;width: 100px;} .right3{background: #09c;overflow: hidden;}
<div class="box" id="box3"> <div class="left3">左側定寬</div> <div class="right3">右側自適應</div> </div>
四、利用 position:absolute 配合 margin 實現flex
.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;}
<div class="box" id="box4"> <div class="left4">左側定寬</div> <div class="right4">右側自適應</div> </div>
五、利用 position:absolute 實現spa
.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;}
<div class="box" id="box5"> <div class="left5">左側定寬</div> <div class="right5">右側自適應</div> </div>
六、利用 display: flex 實現code
.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;}
<div class="box" id="box6"> <div class="left6">左側定寬</div> <div class="right6">右側自適應</div> </div>
七、利用 display: table 實現blog
.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;}
<div class="box" id="box7"> <div class="left7">左側定寬</div> <div class="right7">右側自適應</div> </div>
實現效果以下圖:it
若有表述不許確之處,歡迎指正,歡迎補充,感謝閱讀。io