瀑布流布局(Masonry Layouts)最早出现在Pinterest网站所采用的布局,所以又称为Pinterest布局。
瀑布流布局的核心是基于一个网格的布局,每行包含项目列表的高度是随机的,会随着项目内容动态大小高度自适应。同时每个项目列表呈堆栈形式排列。其中最为关键之处在于,堆栈彼此之间没有多余的间距差存在。
使用Grid网格布局实现自适应瀑布流布局的关键点在于
- 使用
grid-template-columns
和grid-template-rows
分割列和行
.masonry{
display:grid;
grid-gap:0.25em;
grid-template-columns:repeat(auto-fill, minmax(133px, 1fr));
grid-auto-flow: row dense;
grid-flow-rows:minmax(20px, auto);
}
Grid模式填充(repeat-to-fill)
Grid模式填充列后会对内容进行自动布局,开发者只需要指定列数,自适应交给浏览器处理,无需使用媒体查询。
grid-template-columns:repeat(auto-fill, minmax(133px, 1fr));
表示弹性项目至少以133px的宽度自动填充,如果视口宽度足够则平均分配剩余空间给每个项目。这里的auto-fill
是填充模式,填充模式分为auto-fill
和auto-fit
两种,只有在弹性容器宽度大于弹性项目最小宽度总和时才有区别,当弹性容器宽度小于弹性项目总和时auto-fill
和auto-fit
显示效果一致。
auto-fill
和auto-fit
首先会尽可能多的创建基于min
为133px的轨道宽度,针对不足一个轨道的空间,auto-fill
的做法是保留空轨道留白不会折叠空轨道,auto-fit
的做法是将空白轨道空间平均分配给既有弹性项目的轨道。
Grid自动排列算法
由于Grid网格项目中存在自动排列的算法属性grid-auto-flow
grid-auto-flow
属性用于定义Grid网格布局中每个网格项目的“自动流动”状态。
grid-auto-flow: [ row | column ] || dense;
属性值 | 描述 |
---|---|
row | 默认值,表示网格项目一行一行的陈列。 |
column | 表示网格项目以一列一列的排列 |
dense | 多余的网格项目以空白填充 |
- 当没有明确指出网格项目位置时,网格会按照自动排列算法最大化利用可用空间。
- 若当前行没有可用位置时,网格会自动搜索下一行,这样会造成一定的差距,浪费可用剩余空间
- 可设置
grid-auto-flow
中的row
为auto
以切换搜索顺序 -
grid-auto-flow
默认为sparse
,可见其显示的设置为dense
让网格自动填补所有可用的空白空间。
grid-flow-rows:minmax(20px, auto);
- 使用
grid-row
控制每个网格项目占空间大小
grid-row
网格行属性是grid-row-start
和grid-row-end
的缩写形式,用于定义网格项目与网格行相关的尺寸和位置,可通过在网格布局中共享基线、跨度、自动auto
来指定网格区域的行起始和行结束。
grid-row: <grid-line> [ / <grid-line> ] ? where <grid-line>=auto | <custom-ident> | [ <integer> && <custom-ident> ? ] | [ span && [ <integer> || <custom-ident> ] ];
取值 | 描述 |
---|---|
auto | 自动放置,自动跨越(默认跨度为1). |
对于瀑布流中列表项目的控制需分别通过grid-row
和grid-column
来指定列表项目所在区域
.masonry .item:nth-of-type(3n+1) {
grid-row: auto / span 5;
}
完整代码
<div class="container">
<h2 class="title">resposive masonry</h2>
<div class="masonry">
<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>
</div>
.container{
height:100vh;
display: grid;
grid-template-columns: 50vw;
justify-content: center;
padding: 3em;
background-color:#eee;
}
.title{
justify-self: center;
margin: 3em 0;
font: 1em monospace;
background-color:#ddd;
}
.masonry {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(133px, 1fr));
grid-gap: 0.25em;
grid-auto-flow: row dense;
grid-auto-rows: minmax(20px, auto);
background-color:#aaa;
}
.masonry .item {
width: 100%;
background: #222;
color: #ddd;
}
.masonry .item:nth-of-type(3n+1) {
grid-row: auto / span 5;
}
.masonry .item:nth-of-type(3n+2) {
grid-row: auto / span 6;
}
.masonry .item:nth-of-type(3n+3) {
grid-row: auto / span 8;
}
虽然Grid网格布局中的自动排列算法实现瀑布流布局有所帮助,但对堆栈列表项目的高度的控制并不友好。