面試過程中總會文檔兩列布局,左邊等寬,右邊自適應幾種方法?以下提供6種為君解憂
<div id="wrap">
<div id="left"></div>
<div id="right"></div>
</div>
需求就是左側定寬,右側自適應。(height先不用管)
方法一:雙inline-block
#wrap{
width: 100%;
font-size: 0;
}
#left{
width: 200px;
height: 100px;
display: inline-block;
}
#right{
height: 100px;
width: calc(100% - 200px);
display: inline-block;
}
缺點:
為消除html中空格的影響需要把父級的font-size設為0
如果兩邊高度不一樣,需要加vertical-align: top
注意:calc表達式內運算符兩邊要有空格
方法二:雙float
#left{
float: left;
width: 200px;
height: 100px;
}
#right{
float: left;
height: 100px;
width: calc(100% - 200px);
}
本方案和雙inline-block方案原理相同,都是通過動態計算寬度來實現自適應。但是,由於浮動的block元素在有空間的情況下會依次緊貼,排列在一行,所以無需設置display: inline-block;,自然也就少了頂端對齊,空格字符占空間等問題。
A floated box is shifted to the left or right until its outer edge touches the containing block edge or the outer edge of another float.
缺點:
父元素需要清除浮動
方法三: float+margin-left
#left{
float: left;
width: 200px;
height: 100px;
}
#right{
height:100px;
margin-left: 200px;
}
上面兩種方案都是利用了CSS的calc()函數來計算寬度值。下面兩種方案則是利用了block級別的元素盒子的寬度具有填滿父容器,並隨着父容器的寬度自適應的流動特性。block級別的元素會認為浮動的元素不存在,但是inline級別的元素能識別到浮動的元素。
缺點:需要清除浮動,需要計算margin-left
方法四:absolute+margin-left
#left{
position: absolute;
width: 200px;
height: 100px;
}
#right{
height: 100px;
margin-left: 200px;
}
缺點:使用了絕對定位,若是用在某個div中,需要更改父容器的position。
方法五:float+BFC
#wrap{
overflow:hidden;
}
#left{
width: 200px;
height: 100px;
float: left;
}
#right{
height: 100px;
margin-left: 0;
overflow: auto;
}
這種方法同樣是利用了左側浮動,但是右側盒子通過overflow:auto;形成了BFC,因此右側的盒子不會被浮動的元素重疊。
缺點:父元素需要清除浮動。
方法六:flex布局
#wrap{
display: flex;
}
#left{
width: 200px;
height: 100px;
}
#right{
height: 100px;
flex: 1;
}