从零开始学习 grid 网格布局——续集

377 阅读1分钟

这是我参与11月更文挑战的第11天,活动详情查看:2021最后一次更文挑战

网格间隙及简写

  • grid-row-gap grid-column-gap grid-gap:用来设置元素行列之间的间隙大小,推荐使用 row-gap column-gap gap

    设置行间距20px

    .main {
        grid-row-gap: 20px;
    }
    

    image.png

    设置列间距30px

    .main {
        grid-column-gap: 30px;
    }
    

    image.png

    使用复合样式设置行列20px 30px

    .main {
        grid-gap: 20px 30px;
    }
    

    image.png

    上面三个属性虽说都还可以使用,但是已经被淘汰了,推荐使用 row-gap column-gap gap

    .main {
        row-gap: 20px;
        column-gap: 30px;
        /* gap: 20px 30px; */
    }
    

网格对齐方式及简写

  • justify-items align-items place-items:默认值 stretch,指定了子项在网格中的对齐方式;可选值:start | end | center | stretch
<div class="main">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
</div>
.main {
    width: 300px;
    height: 300px;
    background: skyblue;
    display: grid;
    grid-template: 100px 100px 100px
               / 100px 100px 100px;
}
.main div {
    width: 50px;
    height: 50px;
    text-align: center;
    border: 1px dashed #f2f2f2;
    background: pink;
}

此时的网格大小还是100X100

image.png

.main {
    justify-items: center;
    align-items: center;
    place-items: center center; /* 复合写法 */
}

此时格子水平垂直居中

image.png

  • justify-content align-content place-content:默认值 stretch,指定了整个内容区域在容器里面的水平和垂直的位置;可选值:start | end | center | stretch | space-around | space-between | space-evenly

容器内部居中

.main {
    width: 500px;
    height: 500px;
    justify-content: center;
    align-content: center;
}
.main div {
    width: 100px;
    height: 100px;
}

image.png

项目与项目的间隔相等,项目与容器边框之间的间隔也是相等

.main {
    justify-content: space-evenly;
    align-content: space-evenly;
}

image.png

合并简写形式

.main {
    place-content: center space-evenly;
}

image.png