纯css实现瀑布流
太久没写布局了,今天来复习一下各种布局。复习到瀑布流布局的时候,突发奇想,能不能用纯css实现(其实就是想偷懒,不想计算各种高啥的)。结果,真的可以!!!!
代码
<!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; /* 设置列数为3 */
column-gap: 10px; /* 设置列之间的间距 */
}
.waterfall-item {
break-inside: avoid; /* 防止元素在列中间断开 */
margin-bottom: 10px; /* 设置元素之间的间距 */
position: relative;
}
.waterfall-item img {
width: 100%; /* 图片宽度占满父元素 */
display: block; /* 块级显示 */
}
.waterfall-item:before {
content: "";
display: block;
/* 设置占位元素的高度,这里假设图片高度为宽度的1.5倍 */
/* padding-top: calc(100% / 1.5); */
}
</style>
</head>
<body>
<div class="waterfall">
<div class="waterfall-item">
<img
src="https://tse1-mm.cn.bing.net/th/id/OIP-C.G5m45gb0F1xFl8Q0WGxrEQHaEo?w=270&h=180&c=7&r=0&o=5&pid=1.7"
alt=""
/>
</div>
<div class="waterfall-item">
<img
src="https://images.unsplash.com/photo-1660814762331-8e3bcd2ec70e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHx0b3BpYy1mZWVkfDEwfHhIeFlUTUhMZ09jfHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=800&q=60"
alt="Image 1"
/>
</div>
<div class="waterfall-item">
<img
src="https://tse4-mm.cn.bing.net/th/id/OIP-C.jigyRidvrSwB6NDjALtFQAHaD_?w=334&h=180&c=7&r=0&o=5&pid=1.7"
alt="Image 2"
/>
</div>
<div class="waterfall-item">
<img
src="https://images.unsplash.com/photo-1660814762331-8e3bcd2ec70e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHx0b3BpYy1mZWVkfDEwfHhIeFlUTUhMZ09jfHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=800&q=60"
alt=""
/>
</div>
<div class="waterfall-item">
<img
src=" https://tse2-mm.cn.bing.net/th/id/OIP-C.BPTZY8XZik5CK0jk0oRdxAHaE8?w=300&h=200&c=7&r=0&o=5&pid=1.7"
alt=""
/>
</div>
<div class="waterfall-item">
<img
src="https://tse2-mm.cn.bing.net/th/id/OIP-C.C64i5Jj0CbEXYKp0h3CwJgHaE8?w=245&h=180&c=7&r=0&o=5&pid=1.7"
alt=""
/>
</div>
<div class="waterfall-item">
<img
src="https://tse2-mm.cn.bing.net/th/id/OIP-C.YErx6MN5bOJWOPC5t7615QHaJW?w=127&h=180&c=7&r=0&o=5&pid=1.7"
alt=""
/>
</div>
<div class="waterfall-item">
<img
src="https://tse3-mm.cn.bing.net/th/id/OIP-C.CzUsMpGppSJvnoXO7Ef5cQHaLl?w=115&h=180&c=7&r=0&o=5&pid=1.7"
alt=""
/>
</div>
<div class="waterfall-item">
<img
src="https://images.unsplash.com/photo-1660859692002-36833faf17ac?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHx0b3BpYy1mZWVkfDd8eEh4WVRNSExnT2N8fGVufDB8fHx8&auto=format&fit=crop&w=800&q=60"
alt=""
/>
</div>
</div>
</body>
</html>
效果图
1、大屏幕情况
2、小屏幕情况
关键属性:column-count
只要容器设置了宽度,它可以根据容器的宽度来最大限制容器内的列数。兼容性也不错,主流浏览器都支持了
其他详细信息自行查看 column-count - CSS:层叠样式表 | MDN (mozilla.org)
感叹
看来还是要时不时的复习一下,不复习都不知道css已经这么厉害了。另外再感慨一句:学不完,根本学不完,5555~