如何在 div 中垂直對齊元素?


我們可以使用以下任何一種方法輕鬆地在 div 中垂直對齊元素:

  • position 屬性
  • line-height 屬性
  • padding 屬性

讓我們逐一檢視示例:

使用 position 屬性在 div 中垂直對齊元素

position 屬性用於定位元素。它可以與 top、right、bottom 和 left 屬性結合使用,將元素定位到所需位置。以下是 position 屬性的可能值:

  • static - 元素框作為普通文件流的一部分進行佈局,遵循前一個元素和後續元素。

  • relative - 元素的框作為普通流的一部分進行佈局,然後偏移一定距離。

  • absolute - 元素的框相對於其包含塊進行佈局,並且完全從文件的普通流中移除。

  • fixed - 元素框是絕對定位的,具有 position: absolute 所描述的行為。主要區別在於,固定位置元素的包含塊始終是視口。

現在讓我們看一個使用 position 屬性在 div 中垂直對齊元素的示例:

示例

<!DOCTYPE html> <html> <head> <title>Align Elements</title> <style> #demo1 { position: relative; } #demo2 { position: absolute; top: 50%; height: 100px; margin-top: -50px; } #demo1 { background-color: yellow; border: 2px solid gray; height: 15em; } #demo2 { background-color: skyblue; border: 1px solid orange; width: 100%; } </style> </head> <body> <h1>Vertically Align Elements</h1> <p>Use the position property:</p> <div id="demo1"> <div id="demo2"> <p>This is a demo text</p> <p>This is another demo text</p> </div> </div> </body> </html>

使用 line-height 屬性在 div 中垂直對齊元素

line-height 屬性修改構成文字行的內聯框的高度。以下是 line-height 的可能值:

  • normal - 指示瀏覽器將元素中行的的高度設定為“合理”的距離。

  • number - 元素中行的實際高度是此值乘以元素的 font-size。

  • length - 元素中行的的高度是給定的值。

  • percentage - 元素中行的的高度計算為元素 font-size 的百分比。

現在讓我們看一個使用 line-height 屬性在 div 中垂直對齊元素的示例:

示例

<!DOCTYPE html> <html> <head> <title>Align Elements</title> <style> p { margin: 0; } #demo { border: 3px solid yellow; background-color: orange; height: 100px; line-height: 100px; } </style> </head> <body> <h1>Vertically Aligned Element</h1> <p>Use the line-height property:</p> <div id="demo"> <p>This is demo text</p> </div> </body> </html>

使用 padding 屬性在 div 中垂直對齊元素

padding 屬性允許您指定元素內容與其邊框之間應出現多少空間。此屬性的值應為長度、百分比或單詞 inherit。如果值為 inherit,則它將與父元素具有相同的填充。如果使用百分比,則百分比為包含框的百分比。

以下 CSS 屬性可用於控制列表。您還可以使用以下屬性為框的每一側設定不同的填充值:

  • padding-bottom 指定元素的底部填充。
  • padding-top 指定元素的頂部填充。
  • padding-left 指定元素的左側填充。
  • padding-right 指定元素的右側填充。
  • padding 作為前面屬性的簡寫。

現在讓我們看一個使用 padding 屬性在 div 中垂直對齊元素的示例:

示例

<!DOCTYPE html> <html> <head> <title>Align Element</title> <style> .demo { padding: 60px 0; border: 2px solid #5c34eb; background-color: orange; } </style> </head> <body> <h1>Vertically Align Element</h1> <p>Use the padding property:</p> <div class="demo"> <p>This is demo text.</p> <p>This is another text.</p> </div> </body> </html>

更新於: 2022-10-17

6K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.