如何居中一個元素

在本指南中,您可以找到如何將一個元素水平和垂直地居中到另一個元素內的資訊。

居中一個框

要使用 CSS 將一個框居中到另一個框內,您需要在父容器上使用 CSS 框對齊 屬性。由於這些對齊屬性尚未獲得塊級和內聯佈局的瀏覽器支援,您需要將父容器設定為 flexgrid 容器,以啟用對齊功能。

在下面的示例中,我們為父容器設定了 display: flex;然後將 justify-content 設定為 center 以在水平方向上居中,並將 align-items 設定為 center 以在垂直方向上居中。

html
<div class="wrapper">
  <div class="box">center me!</div>
</div>
css
.wrapper {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.box {
  background-color: rgb(69 164 181);
  border-radius: 5px;
  padding: 10px;
  color: white;
}

注意: 您可以使用此技術在另一個元素內對一個或多個元素進行任何型別的對齊。在上面的示例中,您可以嘗試將值更改為 justify-contentalign-items 的任何有效值。

另見