android StaggeredGridLayoutManager 瀑布流 卡顿 android瀑布流实现_android 瀑布流 间距


作者:MudOnTire


前言

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

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


android StaggeredGridLayoutManager 瀑布流 卡顿 android瀑布流实现_ci_02


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

HTML

先构造页面结构:


android StaggeredGridLayoutManager 瀑布流 卡顿 android瀑布流实现_ci_03

Title Goes Here


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?

...more...

在 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 之后会有什么问题吧:


android StaggeredGridLayoutManager 瀑布流 卡顿 android瀑布流实现_CSS_04


可以看到有两个“砖块”的文字跑到上面和图片分开了。所以当设置了 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;  }}

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



android StaggeredGridLayoutManager 瀑布流 卡顿 android瀑布流实现_ide_05



作者:MudOnTire