页面布局技术
CSS Float 布局、Flexbox 弹性布局、Grid 网格布局入门
页面布局技术
HTML 定义结构,CSS 负责布局——从传统的 Float 到现代的 Flexbox 和 Grid。
学完本章你将: 掌握 Float/Flexbox/Grid 三种布局方式的对比和应用。
Float 布局(传统)
html
<style>
.float-left { float: left; width: 70%; }
.float-right { float: right; width: 30%; }
.clearfix::after {
content: "";
display: table;
clear: both;
}
</style>
<div class="clearfix">
<div class="float-left">主内容区</div>
<div class="float-right">侧边栏</div>
</div>
Flexbox 弹性布局(现代)
html
<style>
.flex-container {
display: flex;
/* flex-direction: row; 水平排列(默认) */
/* flex-direction: column; 垂直排列 */
justify-content: space-between; /* 两端对齐 */
align-items: center; /* 垂直居中 */
gap: 20px; /* 间距 */
}
.flex-item { flex: 1; } /* 等分剩余空间 */
</style>
<div class="flex-container">
<div class="flex-item">列 1</div>
<div class="flex-item">列 2</div>
<div class="flex-item">列 3</div>
</div>
Grid 网格布局(最强)
html
<style>
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* 三列比例 */
/* grid-template-columns: repeat(3, 1fr); 三等分 */
gap: 20px;
}
</style>
<div class="grid-container">
<div>侧边栏</div>
<div>主内容</div>
<div>右侧栏</div>
</div>
常见布局模式
html
<!-- 圣杯布局:header → 三列 → footer -->
<div style="display: flex; flex-direction: column; min-height: 100vh;">
<header style="background: #333; color: white; padding: 20px;">头部</header>
<div style="display: flex; flex: 1;">
<nav style="width: 200px; background: #f0f0f0;">导航</nav>
<main style="flex: 1; padding: 20px;">内容</main>
<aside style="width: 200px; background: #f0f0f0;">侧栏</aside>
</div>
<footer style="background: #333; color: white; padding: 10px;">页脚</footer>
</div>