要实现一个纯CSS的四列瀑布流布局,并且确保第一列的高度最高,可以使用CSS的column-count
和column-gap
属性来实现瀑布流效果,然后通过调整内容顺序或使用伪元素来确保第一列的高度最高。
使用column-count
创建四列瀑布流:
column-count
属性可以将内容分成多列。column-gap
属性可以设置列之间的间距。确保第一列高度最高:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>四列瀑布流</title>
<style>
.waterfall {
column-count: 4; /* 分成四列 */
column-gap: 10px; /* 列之间的间距 */
}
.item {
break-inside: avoid; /* 防止内容被分割到不同的列 */
margin-bottom: 10px; /* 项目之间的间距 */
background-color: #f0f0f0;
padding: 10px;
box-sizing: border-box;
}
/* 确保第一列高度最高 */
.item:first-child {
height: 300px; /* 设置第一列的高度 */
}
</style>
</head>
<body>
<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 class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
<!-- 更多项目 -->
</div>
</body>
</html>
column-count: 4;
:将内容分成四列。column-gap: 10px;
:设置列之间的间距为10px。break-inside: avoid;
:防止内容被分割到不同的列。.item:first-child
:通过设置第一个项目的高度,确保第一列的高度最高。如果需要动态调整第一列的高度,可以使用JavaScript来实时计算并设置高度。
document.addEventListener('DOMContentLoaded', function() {
const firstItem = document.querySelector('.item:first-child');
const items = document.querySelectorAll('.item');
let maxHeight = 0;
items.forEach(item => {
if (item.offsetHeight > maxHeight) {
maxHeight = item.offsetHeight;
}
});
firstItem.style.height = `${maxHeight}px`;
});
这个脚本会在页面加载完成后,计算所有项目中的最大高度,并将第一个项目的高度设置为这个最大高度,从而确保第一列的高度最高。
通过CSS的column-count
和column-gap
属性可以轻松实现四列瀑布流布局。要确保第一列的高度最高,可以通过设置第一个项目的高度或使用JavaScript动态调整高度来实现。