前段時(shí)間被面試問(wèn)道左右布局的問(wèn)題械馆,今天就來(lái)親自試驗(yàn)下师坎,看看有多少種方法。
問(wèn):左邊固定像素榕栏,右邊寬度自適應(yīng)畔勤,并且父級(jí)元素的高度是由左邊或右邊的高度撐開(kāi)的。
<div class="main">
<div class="left" contenteditable="true">
左側(cè)內(nèi)容
</div>
<div class="right" contenteditable="true">
右側(cè)內(nèi)容
</div>
</div>
達(dá)到類似如下效果
左側(cè)高時(shí).png
右側(cè)高時(shí).png
-
首先是想到的flex布局
.main {
width: 100%;
display: flex;
border: 1px solid red;
}
.left {
width: 300px;
flex: none;
border-right: 1px solid red;
}
.right {
width: 100%;
}
flex布局可以輕而易舉的實(shí)現(xiàn)效果
-
然后是浮動(dòng)float
.main {
width: 100%;
overflow: hidden;
border: 1px solid red;
}
.left {
width: 300px;
float: left;
border-right: 1px solid red;
}
.right {
margin-left: 300px;
border-left: 1px solid red;
}
浮動(dòng)布局可以將父元素?fù)伍_(kāi)扒磁,但是左右兩個(gè)子元素并不互相影響高度庆揪,所以中間那條線,是左邊和右邊一個(gè)邊框重疊的效果妨托。但如果需要兩個(gè)子元素有不同的背景顏色的話缸榛,就不是這樣的寫(xiě)法了。
浮動(dòng)如果是子元素帶背景兰伤,我是如下寫(xiě)法
.main {
width: 100%;
overflow: hidden;
border: 1px solid red;
position: relative;
}
.main:before{
content: '';
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 300px;
background: orangered;
z-index: -1;
}
.main:after{
content: '';
position: absolute;
top: 0;
bottom: 0;
left: 300px;
right: 0;
background: yellow;
z-index: -1;
}
.left {
width: 300px;
float: left;
background: orangered;
border-right: 1px solid red;
}
.right {
margin-left: 300px;
background: yellow;
border-left: 1px solid red;
}
浮動(dòng)帶背景時(shí)
- 行內(nèi)塊元素 display:inline-block
.main {
width: 100%;
border: 1px solid red;
font-size: 0;
}
.left {
width: 300px;
display: inline-block;
border-right: 1px solid red;
font-size: 14px;
}
.right {
display: inline-block;
border-left: 1px solid red;
height: 100%;
width: calc(100% - 301px);
font-size: 14px;
vertical-align: top;
margin-left: -1px;
}
行內(nèi)塊元素如果要給子元素加背景參考浮動(dòng)即可内颗。
- 表格或display:table
.main {
width: 100%;
border: 1px solid red;
display: table;
}
.left {
width: 300px;
display: table-cell;
border-right: 1px solid red;
background: aquamarine;
}
.right {
display: table-cell;
background: antiquewhite;
}
類表格的布局應(yīng)該說(shuō)是比較簡(jiǎn)單的,也適用子元素帶背景的敦腔。
- grid網(wǎng)格布局
.main {
width: 100%;
border: 1px solid red;
display: grid;
grid-template-columns: 300px auto;
}
.left {
border-right: 1px solid red;
background: aquamarine;
}
.right {
background: antiquewhite;
}
grid布局的寫(xiě)法那就更簡(jiǎn)單了均澳,只需要在父級(jí)元素定義grid即可。
table和grid效果圖.png