"左邊固定,右邊自適應的兩欄布局",其中有老生常談的float
方法,BFC方法,也有CSS3的flex
布局與grid
布局。并非所有的布局都會在開發(fā)中使用,但是其中也會涉及一些知識點。
常用的寬度自適應的方法通常是利用了block
水平的元素寬度能隨父容器調節(jié)的流動特性。另外一種思路是利用CSS中的calc()
方法來動態(tài)設定寬度。還有一種思路是,利用CSS3中的新型布局flex layout
與grid layout
。
效果圖:
HTML布局:
<div class="outer">
<div class="sidebar">固定寬度區(qū)(sideBar)</div>
<div class="content">自適應區(qū)(content)</div>
</div>
<div class="footer">footer</div>
常見的方法:
1、將左側div浮動,右側div設置margin-left
/*方法1*/
.outer{overflow: hidden; border: 1px solid red;}
.sidebar{float: left;width:200px;height: 150px; background: #BCE8F1;}
.content{margin-left:200px;height:100px;background: #F0AD4E;}
2、固定區(qū)采用絕對定位,自適應區(qū)設置margin
/*方法2*/
.outer2{position: relative;height:150px; border: 1px solid red;}
.sidebar2{position: absolute;left: 0;top:0;width:200px;height:100%;background: #BCE8F1;}
.content2{margin-left:200px;height:100px;background: #F0AD4E;}
缺點:
- 使用了絕對定位,若是用在某個div中,需要更改父容器的position。
- 沒有清除浮動的方法,若左側盒子高于右側盒子,就會超出父容器的高度。因此只能通過設置父容器的min-height來放置這種情況。
3、標準瀏覽器的方法
/*方法3*/
.outer3{display: table;width:100%; border: 1px solid red;}
.sidebar3{display:table-cell;width:200px;height:150px;background: #BCE8F1;}
.content3{display:table-cell;height:100px;background: #F0AD4E;}
4、雙float + calc()計算屬性
/*方法4*/
.outer4{overflow: hidden; border: 1px solid red;}
.sidebar4{float:left;width:200px;height:150px;background: #BCE8F1;}
.content4{float:left;width:calc(100% - 200px);height:100px;background: #F0AD4E;}
5、雙inline-block + calc()計算屬性
/*方法5*/
.outer5{box-sizing: content-box;font-size: 0; border: 1px solid red;}
.sidebar5,.content5{display: inline-block;vertical-align: top;box-sizing: border-box;width: 200px;
height:150px; background: #BCE8F1;font-size: 14px;} .outer5
.content5{width:calc(100% - 200px);height:100px;background: #F0AD4E;}
這種方法是通過width: calc(100% - 140px)來動態(tài)計算右側盒子的寬度。需要知道右側盒子距離左邊的距離,以及左側盒子具體的
寬度(content+padding+border),以此計算父容器寬度的100%需要減去的數值。同時,還需要知道右側盒子的寬度是否包含border
的寬度。
在這里,為了簡單的計算右側盒子準確的寬度,設置了子元素的box-sizing:border-box;以及父元素的box-sizing: content-box;。
同時,作為兩個inline-block的盒子,必須設置vertical-align來使其頂端對齊。
另外,為了準確地應用計算出來的寬度,需要消除div之間的空格,需要通過設置父容器的font-size: 0;,或者用注釋消除html中的空格等方法。
缺點:
- 需要知道左側盒子的寬度,兩個盒子的距離,還要設置各個元素的box-sizing
- 需要消除空格字符的影響
- 需要設置vertical-align: top滿足頂端對齊。
6、float + BFC方法(理解CSS布局和BFC =》 https://www.w3cplus.com/css/understanding-css-layout-block-formatting-context.html)
/*方法6*/
.outer6{overflow: auto; border: 1px solid red;}
.sidebar6{float: left;height:150px;background: #BCE8F1;}
.content6{overflow:auto;height:100px;background: #F0AD4E;}
這個方案同樣是利用了左側浮動,但是右側盒子通過overflow: auto;
形成了BFC,因此右側盒子不會與浮動的元素重疊。
7、flex
/*方法7*/
.outer7{display: flex; border: 1px solid red;}
.sidebar7{flex:0 0 200px;height:150px;background: #BCE8F1;}
.content7{flex: 1;height:100px;background: #F0AD4E;}</pre>
flex
可以說是最好的方案了,代碼少,使用簡單。但存在兼容性,有朝一日,大家都改用現代瀏覽器,就可以使用了。
需要注意的是,flex
容器的一個默認屬性值:align-items: stretch;
。這個屬性導致了列等高的效果。
為了讓兩個盒子高度自動,需要設置: align-items: flex-start;