CSS3 实现瀑布流布局(Masonry Layout)主要有两种主流方案:CSS 多列布局(Multi-column) 和 CSS Grid 布局。下面分别介绍,并给出推荐方案。
利用 column-count 将容器分成多列,内容自动向下流动。
<div class="waterfall">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
.waterfall {
column-count: 3; /* 列数 */
column-gap: 16px; /* 列间距 */
}
.item {
break-inside: avoid; /* 防止被截断 */
margin-bottom: 16px;
background: #4caf50;
color: #fff;
padding: 20px;
}
✅ 适合:图片高度不一、顺序不敏感的场景
.waterfall {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 10px;
gap: 16px;
}
.item {
grid-row: span 20; /* 控制高度 */
background: #2196f3;
}
❌ 问题:
<div class="waterfall" id="waterfall"></div>
.waterfall {
position: relative;
width: 100%;
}
.item {
position: absolute;
width: calc(33.333% - 16px);
}
const container = document.getElementById('waterfall');
const items = container.children;
const gap = 16;
const colCount = 3;
const colHeight = new Array(colCount).fill(0);
Array.from(items).forEach(item => {
const minHeight = Math.min(...colHeight);
const colIndex = colHeight.indexOf(minHeight);
item.style.left = colIndex * (100 / colCount) + '%';
item.style.top = minHeight + 'px';
colHeight[colIndex] += item.offsetHeight + gap;
});
container.style.height = Math.max(...colHeight) + 'px';
✅ 优点
❌ 缺点
| 方案 | 是否推荐 | 是否纯 CSS | 顺序 | 难度 |
|---|---|---|---|---|
| column-count | ⭐⭐⭐ | ✅ | 纵向 | ⭐ |
| grid 固定高度 | ⭐⭐ | ✅ | 横向 | ⭐⭐ |
| grid + JS | ⭐⭐⭐⭐⭐ | ❌ | 横向 | ⭐⭐⭐ |
| Masonry JS | ⭐⭐⭐⭐ | ❌ | 横向 | ⭐⭐⭐ |
resize 重新布局requestAnimationFrame如果你愿意,我可以:
你更偏向哪种使用场景?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。