Grid 容器属性篇(三) | 每天学一点Grid | 每天学一点Grid

157 阅读3分钟

Grid 容器属性篇(三) | 每天学一点Grid | 每天学一点Grid

“开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 10 天,点击查看活动详情

Grid 容器属性

本文我们先来看一下部分容器属性,grid-auto-flow 、justify-items、align-items、place-items 属性

1. grid-auto-flow 属性

划分网格以后,容器的子元素会按照顺序,自动放置在每一个网格。

默认的放置顺序是“先行后列”,即先填满第一行,再开始放入第二行,示意图如下:

image.png

这个顺序由 grid-auto-flow 属性决定,默认值是 row,即“先行后列”。也可以将它设成 column,变成“先列后行”。

示意图如下:

image.png

来看一个具体的示例:

.wrapper {
    width: 450px;
    height: 450px;
    background: #f3f3f3;
    text-align: center;
    display: grid;
    grid-template-columns: 150px 150px 150px;
    grid-template-rows: 150px 150px 150px;
    grid-auto-flow: column;
}

效果:

grid-auto-flow 属性除了设置成 rowcolumn,还可以设成 row densecolumn dense

注:dense(adj):密集的; 稠密的;

这两个值主要用于,某些项目指定位置以后,剩下的项目怎么自动放置。

来看一个具体的示例:

.wrapper {
    width: 450px;
    height: 450px;
    background: #f3f3f3;
    text-align: center;
    display: grid;
    grid-template-columns: 150px 150px 150px;
    grid-template-rows: 150px 150px 150px;
}
.item:first-of-type {
    background: #ef342a;
    grid-column-start: 1;
    grid-column-end: 3;
}

.item:nth-of-type(2) {
    background: #00a0a0;
    grid-column-start: 1;
    grid-column-end: 3;
}

注:grid-column-startgrid-column-end 分别表示左边框所在的垂直网格线和右边框所在的垂直网格线,属于项目属性,稍后会具体进行介绍。

当前效果如下:

上图中,1 号项目后面的位置是空的,这是因为 3 号项目默认跟着 2 号项目,所以会排在 2 号项目后面。

现在修改设置,将 grid-auto-flow 属性设为 row dense,表示“先行后列”,并且尽可能紧密填满,尽量不出现空格。

.wrapper {
    width: 450px;
    height: 450px;
    background: #f3f3f3;
    text-align: center;
    display: grid;
    grid-template-columns: 150px 150px 150px;
    grid-template-rows: 150px 150px 150px;
    grid-auto-flow: row dense;
}

效果如下:

如果将 grid-auto-flow 属性值修改为 column dense,则是“先列后行”,效果如下:

2. justify-items、align-items、place-items 属性

justify-items 属性设置单元格内容的水平位置(左中右),align-items 属性设置单元格内容的垂直位置(上中下)。

这两个属性的写法完全相同,都可以取下面这些值:

  • start:对齐单元格的起始边缘
  • end:对齐单元格的结束边缘
  • center:单元格内部居中
  • stretch:拉伸,占满单元格的整个宽度(默认值)

来看一个具体的示例:

.wrapper {
    width: 450px;
    height: 450px;
    background: #f3f3f3;
    text-align: center;
    display: grid;
    grid-template-columns: 150px 150px 150px;
    grid-template-rows: 150px 150px 150px;
    justify-items: center;
    align-items: center;
}

.item {
    text-align: center;
    border: 1px solid #fff;
    color: #fff;
    font-weight: bold;
    /* line-height: 150px;  去除每个项目的行高 */
}

效果如下:

至于其他属性值,这里不再一一进行示例,仅给出示意图。

justify-items 值为 start 时效果示意图如下:

image.png

justify-items 值为 end 时效果示意图如下:

image.png

justify-items 值为 center 时效果示意图如下:

image.png

justify-items 值为 stretch 时效果示意图如下:

image.png

align-items 值为 start 时效果示意图如下:

image.png

align-items 值为 end 时效果示意图如下:

image.png

align-items 值为 center 时效果示意图如下:

image.png

align-items 值为 stretch 时效果示意图如下:

image.png

place-items 属性是 align-items 属性和 justify-items 属性的合并简写形式。

语法如下:

place-items: <align-items> <justify-items>;

例如: place-items: start end;

如果省略第二个值,则浏览器认为与第一个值相等。