前言
相較於定位,浮動來說,Flex和Grid才是真正為了瀏覽器布局而開發的CSS布局系統。兩列布局是我們經常使用的一種布局
1 – 經典兩列布局
效果如圖
<style> * { margin: 0; padding: 0; } #left-bar { background-color: red; height: 100vh; width: 300px; } #content { background-color: blue; height: 100vh; flex-grow: 1; } body { display: flex; flex-direction: row; flex-wrap: nowrap; } </style> <div id="left-bar"> </div> <div id="content"> </div>
1.1 – 代碼解析:
首先我們創建了兩個Box: left-bar 和 content. 指定 left-bar 為紅色, content 為藍色
然后我們給 left-bar 的高度設定為 100vh (屏幕的100%高度) 並給 left-bar 指定了一個固定的寬度
對父容器body開啟flex布局,將派來方式改為 row , 給content指定flex-grow為1, content就會默認填滿剩余的所有空間
2- 兩行布局
<!-- 兩行布局 --> <style type="text/css"> * { margin: 0; padding: 0; } #line-top { background-color: aqua; width: 100vw; height: 100px; } #line-content { width: 100vw; background-color: aquamarine; flex-grow: 1; } #footer { height: 100px; background-color: beige; } body { /* 指定100vw和vh很重要,如果content容器的內容比較少,可能撐不開整個屏幕 */ width: 100vw; height: 100vh; display: flex; flex-direction: column; flex-wrap: nowrap; } </style> <div id="line-top"> </div> <div id="line-content"> <!-- <div style="height: 1000px;"></div> -->
flex詳情:https://www.ruanyifeng.com/blog/2015/07/flex-grammar.html