position: relative 與 position: absolute 的搭配,是 CSS 中最實用的組合之一。本文用一個新聞列表框當例子,說明如何用這對組合做出「標題欄固定於容器頂部、內容區自行填滿」的效果。
思路很直接:外層容器設 position: relative 作為定位基準,並預留上方內距;標題欄則設為 position: absolute 貼齊容器頂端,寬度撐滿整個容器。因為標題欄脫離了文檔流,內容區不必為它讓位,靠容器的 padding-top 就能拉出空間。
完整代碼:
<style>
* {
margin: 0px;
padding: 0px;
list-style-type: none;
font-family: arial;
font-size: 11px;
}
body { padding: 100px; }
.TableShow {
width: 480px;
position: relative;
border: 1px solid #eee;
padding: 34px 10px 10px 10px;
}
.TableShow ul {
position: absolute;
width: 100%;
height: 24px;
line-height: 24px;
left: 0px;
top: 0px;
background: #eee;
}
.TableShow .title { float: left; margin-left: 10px; }
.TableShow .more { float: right; margin-right: 10px; }
</style>
結構部分,標題欄放在內容之前,內部用浮動把標題推到左側、「More」推到右側:
<div class="TableShow">
<ul>
<li class="more">More</li>
<li class="title">Title</li>
</ul>
<dl>
<dt>Title : News Center List</dt>
<dt>Title : News Center List</dt>
<dt>Title : News Center List</dt>
</dl>
</div>
另外示例中用 jQuery 為每個 dt 前面加上符號,示範了如何以腳本補充裝飾性內容:
$(document).ready(function() {
$(".TableShow dt").prepend("> ")
});
這個模式可以延伸成標籤頁、卡片抬頭、模組視窗標題列等各種場合。要點只有一個:relative 給絕對定位的元素提供坐標系。理解了這層關係,這類「浮動於容器之上」的布局就很難把你難住了。