完整代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>固定寬度自適應高度版面</title>
<style>
body {
background: #e1ddd9;
font: 12px/1.5 Verdana, Arial, Helvetica, sans-serif;
color: #564b47;
padding: 20px; margin: 0;
text-align: center;
}
#content {
width: 550px;
margin: 0 auto; /* 水平置中 */
padding: 0;
background: #fff;
border: 1px dashed #564b47;
text-align: left;
vertical-align: middle; /* 僅對 inline-block 生效,此處無實際作用 */
}
h1 {
margin: 0; padding: 5px 10px;
font-size: 11px; text-transform: uppercase;
text-align: right; color: #564b47;
background: #90897a;
}
p, pre { margin: 0; padding: 5px 10px; }
a { color: #ff66cc; font-size: 11px; text-decoration: none; }
pre { font-family: Courier, Monaco, monospace; color: #564b47; }
</style>
</head>
<body>
<div id="content">
<p><b>Center a FIXED BOX</b><br><br>
This BOX has a fixed width.<br>
It is centered and adjusts to the browser window.<br>
The height adjusts to the content.<br>
<a href="/">More templates</a><br>
</p>
<pre>/* CSS 代碼展示 */</pre>
<p><img src="xhtml10.gif" alt="" width="80" height="15">
<img src="css.gif" alt="" width="80" height="15"></p>
</div>
</body>
</html>
核心機制
#content { width:550px; margin:0 auto; }:固定寬度 + 左右自動邊距 = 水平置中(需標準模式 DOCTYPE)。
- 無
height 設定 → 高度完全由內容撐開,自適應無上限。
border:1px dashed 視覺化容器邊界,驗證高度自適應效果。
body { padding:20px; text-align:center }:頁面邊距 + IE5.x 置中相容。
避坑提醒
vertical-align:middle 於區塊元素無效,僅對 inline-block/table-cell 生效,此處可刪除。
- 若內容包含浮動元素,需在
#content 加 overflow:hidden 或 clearfix,否則高度塌陷邊框會縮成一線。