如何使用 CSS 將元素垂直和水平居中?


要使用 CSS 將元素垂直和水平居中,可以使用 **justify-content** 和 **align-items** 屬性。在我們的示例中,我們使用了 flex。

justify-content 屬性

在 CSS 中,justify-content 屬性用於水平對齊專案。CSS justify-content 屬性的語法如下:

Selector {
   display: flex;
   justify-content: /*value*/
}

以下是屬性值:

  • **flex-start** - 彈性專案放置在容器的開頭。這是預設值。

  • **flex-end** - 彈性專案放置在容器的末尾

  • **center** - 彈性專案放置在容器的中心

  • **space-between** - 彈性專案之間會有間距

  • **space-around** - 彈性專案前後以及之間會有間距

  • **space-evenly** - 彈性專案周圍會有相等的間距

align-items 屬性

在 CSS 中,align-items 屬性用於設定 flexbox 中 flex-items 的預設對齊方式。它垂直對齊專案。

語法

CSS align-items 屬性的語法如下:

Selector {
   display: flex;
   justify-content: /*value*/
}

以下是屬性值:

  • **stretch** - 彈性專案拉伸以適應容器

  • **center** - 彈性專案放置在容器的中心

  • **flex-start** - 彈性專案放置在容器的開頭

  • **flex-end** - 彈性專案放置在容器的末尾

建立元素

假設我們要對齊一個 <h2> 元素。<h2> 元素用於在網頁上建立標題:

<h2>This text is centered vertically and horizontally both</h2>

將元素設定在 div 內部

要水平居中對齊按鈕,請將按鈕元素設定在 div 內部:

<div class="centered">
   <h2>This text is centered vertically and horizontally both</h2>
</div>

設定 div 的樣式並居中對齊

要垂直居中對齊,請使用 **align-items** 屬性。要水平居中對齊,請使用 **justify-content** 屬性。將兩個值的屬性值都設定為 center:

.centered {
   display: flex;
   justify-content: center;
   align-items: center;
   height: 200px;
   border: 3px solid rgb(0, 70, 128);
}

示例

讓我們看看示例

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      }
      .centered {
         display: flex;
         justify-content: center;
         align-items: center;
         height: 200px;
         border: 3px solid rgb(0, 70, 128);
      }
   </style>
</head>
<body>
   <h1>Centering Example</h1>
   <div class="centered">
      <h2>This text is centered vertically and horizontally both</h2>
   </div>
</body>
</html>

更新於: 2023年11月16日

296 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.