第九讲:auto-fill
auto-fill 属于容器属性的一个方法,用于grid布局下主元素的 grid-template-rows 和 grid-template-columns 两个属性中的 repeat 函数,表达主元素子项目(即子元素)在行和列中的自动填充方式,换言之,如果 grid-template-rows 和 grid-template-columns 属性使用了 auto-fill(并规定了尺寸——必须),则子项目们会根据父元素的宽高自动“调整队伍”。以下示例中,父窗体可以通过拖动右下角改变宽度,试着左右改变父元素的大小,查看其内元素排列的动态变化:
上面效果的核心 CSS 代码如下:
#autoFill {
margin: auto;
padding: 10px;
width: 400px;
height: 200px;
position: relative;
overflow: hidden;
resize: horizontal;
display: grid;
grid-template-rows: repeat(auto-fill, 40px);
grid-template-columns: repeat(auto-fill, 40px);
gap: 4px;
}
#autoFill > span {
width: 40px;
height: 40px;
border: 1px solid teal;
display: grid;
place-items: center;
border-radius: 50%;
}
当我们固定了 grid 子项目的尺寸(比如上例中的 40*40 的 span 标签),但父窗口可能存在尺寸上的不确定性时(比如上例中的宽度可以调整,又如,假若父元素设置了 min-height、内部元素高度总和如果超出 min-height 的值),或者在子项目(子元素)的数量不确定时(例如JS根据需要动态生成子元素的情形),auto-fill 就显示出了它的优越性——它能令子元素像文本流一样自动排列且能自动换行。
grid布局中,相同应用情景下,还有一个 auto-fit 方法,语法和功能都和 auto-fill 极其相似,上例,完全可以使用 auto-fit 取代 auto-fill,根本看不出二者有什么区别(当然,两者实际上是有区别的,这里不谈)。以下示例,使用 auto-fit 代替了 auto-fill,仅将 repeat(auto-fit, 40px) 改为了 repeat(auto-fit, 30px) 以示父元素对行列尺寸的定义有多重要(它会无视子项目定义的尺寸,虽然子项目的尺寸不会被破坏):
小结:本讲介绍了 grid-template-rows/columns 的 repeat 函数会用到的 auto-fill 方法,顺带也把 auto-fit 拉下水。auto-fill 和 auto-fit 方法极其相似,都能令 grid 子项目群根据父元素的尺寸以自动填充(适应)的方式调整排列样式。其语法为:
grid-template-rows: repeat(auto-fill, 尺寸);
grid-template-columns: repeat(auto-fill, 尺寸);
grid-template-rows: repeat(auto-fit, 尺寸);
grid-template-columns: repeat(auto-fit, 尺寸);