自適應佈局的實現方式有很多種,本文記錄一種以 position 屬性為核心的佈局思路。這種做法在後續開發中會經常用到,因此特別整理出來備查。
透過絕對定位搭配 top、bottom、left、right 同時設值,可以讓元素自動填滿剩餘空間,從而達到自適應的效果,而不必依賴固定寬高。
<html style="margin:0; padding:0; width:100%; height:100%;">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>自適應佈局</title>
</head>
<body style="margin:0; padding:0; width:100%; height:100%;">
<div style="width:200px; height:99.5%; background-color:#999;">
<div style="width:200px; height:250px; background:#b2b2b2; border:1px solid red;">
<a href="www.baidu.com">baidu</a>
</div>
<div style="width:200px; background:#2b2b2b; color:#fff;
position:absolute; top:250px; bottom:0px; left:0px; border:1px solid blue;">
內容區
</div>
</div>
<div style="height:100%; background:#efefef; color:#2b2b2b;
position:absolute; top:0px; bottom:0px; left:200px; right:0px;">
<div style="width:100%; height:60px; background:blue; color:#fff;">content</div>
<div style="width:200px; background:#2b2b2b; color:#fff;
position:absolute; top:60px; bottom:0px; left:0px; border:1px solid blue;">
內容區
</div>
</div>
</body>
</html>
關鍵在於:當一個絕對定位元素同時設定了對立的兩個偏移(例如 top 與 bottom),瀏覽器會自動把它的尺寸拉伸填滿,這正是自適應的核心。搭配百分比寬高,就能構出隨視窗伸縮的版面。