如何垂直对齐 div 中的元素?

htmlweb developmentfront end technology更新于 2024/6/4 17:16:17

我们可以使用以下任意一种方式轻松地垂直对齐 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 是上述属性的简写。

现在让我们看一个使用 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>

相关文章


有用资源