<返回更多

纯CSS实现瀑布流(Masonry)

2020-07-22    
加入收藏
「干货」纯CSS实现瀑布流(Masonry)

 

作者:MudOnTire

转发链接:https://segmentfault.com/a/1190000023103516

前言

瀑布流提供了一种错落有致的美观布局,被各种注重交互品味的素材网站(如:花瓣、unsplash)广泛应用。社区也提供了不少瀑布流布局的工具,如:masonry 、colcade 等。常规的实现瀑布流的做法是用 JS 动态的计算“砖块”的尺寸和位置,计算量大、性能差。今天给大家介绍一种使用纯 css 实现瀑布流的方法,简洁优雅。主要使用到了 CSS 中的多列属性 columns。

在使用一个比较陌生的 CSS 属性之前,习惯性的了解一下它的兼容性,去 caniuse.com 瞅一眼:

「干货」纯CSS实现瀑布流(Masonry)

 

看着兼容性还不错,那就放心的用吧。

html

先构造页面结构:

<div class="masonry">
  <div class="item">
    <img src="http://source.unsplash.com/random/400x600" />
    <h2>Title Goes Here</h2>
    <p>
      Lorem, ipsum dolor sit amet consectetur adipisicing elit. Quis quod et
      deleniti nobis quasi ad, adipisci perferendis totam, ducimus incidunt
      dolore aut, quae quaerat architecto quisquam repudiandae amet nostrum
      quidem?
    </p>
  </div>
  ...more...
</div>

在 div.masonry 容器中可以塞进任意多的 “砖块” div.item,“砖块” 中的图片可以从 unsplash 中随机获取,且可以制定图片的尺寸。

CSS

容器:

.masonry {
  width: 1440px; // 默认宽度
  margin: 20px auto; // 剧中
  columns: 4; // 默认列数
  column-gap: 30px; // 列间距
}

砖块:

.item {
  width: 100%;
  break-inside: avoid;
  margin-bottom: 30px;
}
.item img {
  width: 100%;
}
.item h2 {
  padding: 8px 0;
}
.item P {
  color: #555;
}

上面的样式其他都挺好理解,唯独 break-inside 这个属性比较陌生。让我们看一下去掉 break-inside 之后会有什么问题吧:

「干货」纯CSS实现瀑布流(Masonry)

 

可以看到有两个“砖块”的文字跑到上面和图片分开了。所以当设置了 break-inside: avoid 之后可以避免“砖块”内部的内容被断开。

不同屏幕尺寸适配

以上样式默认适配 PC,在其他尺寸设备上需要重新设置列数、列间距等样式,可以通过 media query 进行适配,比如:

ipad pro:
@media screen and (min-width: 1024px) and (max-width: 1439.98px) {
  .masonry {
    width: 96vw;
    columns: 3;
    column-gap: 20px;
  }
}
ipad:
@media screen and (min-width: 768px) and (max-width: 1023.98px) {
  .masonry {
    width: 96vw;
    columns: 2;
    column-gap: 20px;
  }
}
mobile:
@media screen and (max-width: 767.98px) {
  .masonry {
    width: 96vw;
    columns: 1;
  }
}

注意:屏幕尺寸区间不要有交集,也不要有缺口!

好了,大功告成,来张全家福!

「干货」纯CSS实现瀑布流(Masonry)

 

作者:MudOnTire
转发链接:https://segmentfault.com/a/1190000023103516

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>