自適應佈局在實戰中越來越普遍。核心技術:**聖杯佈局(雙飛翼佈局)**,利用浮動 + 負邊距實現,**符合漸進增強理念**:重要內容優先解析(DOM 前置),次要內容後置。三大經典場景完整代碼:
核心技巧:`.wrap` 100% 浮動承載內容區,`.content` 左邊距預留側欄寬度,`.right` 負邊距 -100% 回拉至左側。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>左固右適 - 聖杯佈局</title>
<style>
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` 右邊距預留,`.right` 負邊距 -200px(自身寬度)回拉。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>右固左適 - 聖杯佈局</title>
<style>
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>
</head>
<body>
<div class="wrap"><div class="content">content</div></div>
<div class="right">aside</div>
</body>
</html>
核心技巧:`.content` 雙側邊距預留,`.left` -100% 回拉至最左,`.right` -200px 回拉至左欄後方。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>左右固中適 - 雙飛翼佈局</title>
<style>
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; background: red; float: left; margin-left: -200px; }
</style>
</head>
<body>
<div class="wrap"><div class="content">content</div></div>
<div class="left">aside</div>
<div class="right">aside</div>
</body>
</html>
| 方案 | 優勢 | 劣勢 | 適用場景 |
|---|---|---|---|
| Flexbox | 代碼極簡、自動等高、對齊強大 | 舊瀏覽器需降級 | 現代項目首選 |
| CSS Grid | 二維佈局原生支持、語義清晰 | IE 不支持 | 複雜網格佈局 |
| 聖杯/雙飛翼 | 兼容性極佳(IE6+)、DOM 順序可控 | 代碼較繁瑣、需固定高度或清除浮動 | 老項目維護、極致兼容要求 |
掌握浮動負邊距佈局原理,不僅能應對歷史項目,更能深度理解 CSS 視覺格式化模型——這是通往 Flex/Grid 現代佈局大門的基石階梯。