css實現兩欄佈局,左側固定寬,右側自適應的7中方法

一個面試會問的問題,如何實現兩個盒子,左側固定寬度,右側自適應。css

一、利用 calc 計算寬度的方法web

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>

二、利用 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>

三、利用 float 配合 overflow 實現dom

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>

四、利用 position:absolute 配合 margin 實現flex

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>

五、利用  position:absolute 實現spa

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>

六、利用 display: flex 實現code

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>

七、利用 display: table 實現blog

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>

實現效果以下圖:it

若有表述不許確之處,歡迎指正,歡迎補充,感謝閱讀。io

相關文章
相關標籤/搜索