等高布局实现方案
多种 CSS 等高布局的实现方式
问题
实现多列等高布局,无论各列内容多少,所有列的高度都与最高列保持一致。
解答
方案一:Flexbox
最简单的现代方案,flex 子项默认等高。
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: flex;
}
.column {
flex: 1;
padding: 20px;
}
.col1 { background: #f0f0f0; }
.col2 { background: #e0e0e0; }
.col3 { background: #d0d0d0; }
</style>
</head>
<body>
<div class="container">
<div class="column col1">
<p>短内容</p>
</div>
<div class="column col2">
<p>中等内容</p>
<p>中等内容</p>
<p>中等内容</p>
</div>
<div class="column col3">
<p>长内容</p>
<p>长内容</p>
<p>长内容</p>
<p>长内容</p>
<p>长内容</p>
</div>
</div>
</body>
</html>
方案二:Grid
Grid 布局同样默认等高。
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* 三列等宽 */
}
.column {
padding: 20px;
}
方案三:Table 布局
利用表格单元格天然等高的特性。
.container {
display: table;
width: 100%;
}
.column {
display: table-cell;
padding: 20px;
}
方案四:padding + 负 margin
兼容老浏览器的经典方案。
.container {
overflow: hidden; /* 关键:裁剪超出部分 */
}
.column {
float: left;
width: 33.33%;
padding-bottom: 9999px; /* 大 padding 撑开 */
margin-bottom: -9999px; /* 负 margin 抵消 */
}
方案五:绝对定位
适用于固定列数的场景。
.container {
position: relative;
}
.column {
position: absolute;
top: 0;
bottom: 0; /* top 和 bottom 都为 0,自动撑满高度 */
}
.col1 { left: 0; width: 33.33%; }
.col2 { left: 33.33%; width: 33.33%; }
.col3 { left: 66.66%; width: 33.33%; }
完整对比示例
<!DOCTYPE html>
<html>
<head>
<style>
h3 { margin-top: 30px; }
/* Flexbox */
.flex-container {
display: flex;
}
.flex-container .column {
flex: 1;
padding: 20px;
}
/* Grid */
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.grid-container .column {
padding: 20px;
}
/* Table */
.table-container {
display: table;
width: 100%;
}
.table-container .column {
display: table-cell;
padding: 20px;
}
/* 颜色 */
.col1 { background: #ffcccc; }
.col2 { background: #ccffcc; }
.col3 { background: #ccccff; }
</style>
</head>
<body>
<h3>Flexbox</h3>
<div class="flex-container">
<div class="column col1">短</div>
<div class="column col2">中<br>中</div>
<div class="column col3">长<br>长<br>长</div>
</div>
<h3>Grid</h3>
<div class="grid-container">
<div class="column col1">短</div>
<div class="column col2">中<br>中</div>
<div class="column col3">长<br>长<br>长</div>
</div>
<h3>Table</h3>
<div class="table-container">
<div class="column col1">短</div>
<div class="column col2">中<br>中</div>
<div class="column col3">长<br>长<br>长</div>
</div>
</body>
</html>
关键点
- Flexbox:
align-items默认值是stretch,子项自动拉伸等高 - Grid:网格项默认填满单元格高度
- Table:表格单元格天然等高,兼容性最好
- padding + 负 margin:视觉欺骗,实际高度不等,但看起来等高
- 推荐方案:现代项目用 Flexbox 或 Grid,需要兼容 IE9 以下用 Table
目录