實現 grid 佈局的水平居中和垂直居中可以使用以下兩種方式:
·
- 使用 align-items 和 justify-items 屬性
可以將 grid 容器設置爲網格項目在水平和垂直方向都居中,方法是將 align-items 和 justify-items 屬性都設置爲 center。例如:
.container {
display: grid;
align-items: center;
justify-items: center;
}
- 使用 grid-template-areas 屬性
可以使用 grid-template-areas 屬性,將所有的網格項目都放置在 grid 容器的中心區域,從而實現水平居中和垂直居中。例如:
.container {
display: grid;
grid-template-areas: " center " ;
justify-content: center;
align-content: center;
}
.center {
grid-area: center;
}
在這個示例中,grid-template-areas 屬性設置了只有一個區域 center,而其他網格項目則被隱藏在邊緣區域中;justify-content 和 align-content 屬性將 center 區域放置於 grid 容器的中心。
以上兩種方式都可以實現 grid 佈局的水平居中和垂直居中,具體應該根據實際情況選擇。