自適應布局可分為高度與寬度兩類,方法有很多。以下以三欄布局為例說明,理解了三欄,兩欄的原理也一樣。
效果圖如下(高度自適應與寬度自適應):


原理是把每個模塊設為絕對定位,再將中間自適應模塊的 top 與 bottom 分別設為頂部與底部模塊的高度,中間模塊的高度便自動填滿。
<body>
<div class="top">120px</div>
<div class="main">自適應</div>
<div class="bottom">120px</div>
</body>
.top { width: 100%; height: 120px; position: absolute; background-color: greenyellow; }
.main { position: absolute; width: 100%; top: 120px; bottom: 120px; background-color: azure; height: auto; }
.bottom { position: absolute; bottom: 0; width: 100%; height: 120px; background-color: greenyellow; }有三種方法:絕對定位、margin 優先渲染、自身浮動。
a. 絕對定位:針對自適應模塊使用絕對定位,把 left 與 right 設為左右兩欄的寬度(原理同高度自適應),左右兩欄則各自浮動。
<body>
<div class="left">200px</div>
<div class="main">自適應</div>
<div class="right">200px</div>
</body>
html, body { margin: 0; height: 100%; padding: 0; font-size: 30px; font-weight: 500; text-align: center; }
.left, .right { width: 200px; display: inline; height: 100%; background-color: greenyellow; }
.left { float: left; }
.right { float: right; }
.main { position: absolute; left: 200px; right: 200px; height: 100%; background-color: azure; display: inline; }b. 中間欄優先渲染:關鍵是讓內容在 HTML 中放在最前面。自適應的 div 必須放在 left、right 之前,並包在一個父 div 裡;父 div、left、right 都向左浮動,再對自適應 div 設 margin: 0 200px,left 設 margin-left:-100%,right 設 margin-left:-200px。
<body>
<div class="main"><!-- 用一個父 div 包住 -->
<div class="content">自適應</div>
</div>
<div class="left">200px</div>
<div class="right">200px</div>
</body>
html, body { margin: 0; height: 100%; padding: 0; font-size: 30px; font-weight: 500; text-align: center; }
.main { width: 100%; height: 100%; float: left; }
.main .content { margin: 0 200px; background-color: azure; height: 100%; }
.left, .right { width: 200px; height: 100%; float: left; background-color: greenyellow; }
.left { margin-left: -100%; /* important */ }
.right { margin-left: -200px; /* important */ }c. 自身浮動:中間欄設 margin,左右兩欄各自浮動。注意使用此法時,自適應欄在 HTML 中必須放在 left、right 之後。
<body>
<div class="left">200px</div>
<div class="right">200px</div>
<div class="main">自適應</div>
</body>
html, body { margin: 0; height: 100%; padding: 0; font-size: 30px; font-weight: 500; text-align: center; }
.main { margin: 0 200px; height: 100%; background-color: azure; }
.left, .right { width: 200px; height: 100%; background-color: greenyellow; }
.left { float: left; }
.right { float: right; }