如何在 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.