Grid去做水平垂直居中

實現 grid 佈局的水平居中和垂直居中可以使用以下兩種方式:
·

  1. 使用 align-items 和 justify-items 屬性

可以將 grid 容器設置爲網格項目在水平和垂直方向都居中,方法是將 align-items 和 justify-items 屬性都設置爲 center。例如:

.container {
  display: grid;
  align-items: center;
  justify-items: center;
}
  1. 使用 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 佈局的水平居中和垂直居中,具體應該根據實際情況選擇。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章