自適應布局在實際專案中越來越普遍。以下分享三個 demo,主要采用「聖杯布局」(也稱雙翼布局)的做法,核心技巧是浮動加上負的 margin。
聖杯布局有個很好的性質:它符合前端開發中「漸進增強」的理念。因為瀏覽器是從上而下解析 DOM,聖杯布局能把頁面中最重要的內容區放在 DOM 的前端優先解析,而次要的側欄內容則排在後方。這對載入速度與 SEO 都有實際好處。
理解這三個例子之後,實際專案中絕大多數的自適應布局問題都能解決。至於絕對定位布局,原理懂了之後會發現它更簡單,這裡就不另外說明了。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>左側固定,右側自適應</title>
<style type="text/css">
body { margin: 0; padding: 0; }
.wrap { width: 100%; float: left; }
.content { height: 300px; background: green; margin-left: 200px; }
.right { width: 200px; height: 300px; background: red; float: left; margin-left: -100%; }
</style>
</head>
<body>
<div class="wrap">
<div class="content">content</div>
</div>
<div class="right">aside</div>
</body>
</html>
原理:content 在 DOM 中排在最前面(優先解析),用 margin-left: 200px 為左側欄留出空間;右側欄則用 margin-left: -100% 把自己拉到上一行、貼齊右緣。負 margin 的百分比是相對於父容器寬度計算,因此 -100% 恰好等於一整個容器寬。
<style type="text/css">
body { margin: 0; padding: 0; }
.wrap { width: 100%; float: left; }
.content { height: 300px; background: green; margin-right: 200px; }
.right { width: 200px; height: 300px; background: red; float: left; margin-left: -200px; }
</style>
<div class="wrap">
<div class="content">content</div>
</div>
<div class="right">aside</div>
差異:content 改用 margin-right 留白,側欄則用固定的 -200px 位移,因為此時需要移動的距離就是側欄自身的寬度。
<style type="text/css">
body { margin: 0; padding: 0; }
.wrap { width: 100%; float: left; }
.content {
height: 300px;
background: green;
margin-left: 200px;
margin-right: 200px;
}
.left {
width: 200px; height: 300px;
float: left; background: yellow;
margin-left: -100%;
}
.right {
width: 200px; height: 300px;
float: left; background: red;
margin-left: -200px;
}
</style>
<div class="wrap">
<div class="content">content</div>
</div>
<div class="left">aside</div>
<div class="right">aside</div>
原理:content 同時留出左右兩側空間;left 用 -100% 拉到最左;right 則用 -200px 從 content 的右側邊界往左拉一個自身寬度,剛好貼齊右緣。三個元素都在同一行,DOM 順序卻是 content 優先,這正是聖杯布局的精髓。
這三個版型用 Flexbox 都只要三行程式碼:
/* 左側固定,右側自適應 */
.container { display: flex; }
.left { width: 200px; }
.right { flex: 1; }
/* 左右固定,中間自適應 */
.left, .right { width: 200px; }
.content { flex: 1; }
或用 Grid 更直觀:
.container {
display: grid;
grid-template-columns: 200px 1fr 200px;
}
負 margin 的聖杯技巧今天仍有其價值——它解釋了「為什麼負 margin 能把元素拉到上一行」,這個原理在製作重疊卡片、超出容器的裝飾元素時依然用得到。但若是單純的三欄布局,Grid 與 Flex 無論在程式碼量、可讀性還是維護成本上都遠勝前者。