首页 > 文章列表 > 如何在一个div中垂直对齐元素?

如何在一个div中垂直对齐元素?

元素 DIV 垂直对齐
172 2023-09-17

我们可以使用以下任何一种方式轻松地在一个div中垂直对齐元素 −

  • position属性
  • 行高属性
  • 填充属性

让我们逐个看例子 -

使用position属性在div中垂直对齐元素

position 属性用于定位元素。它可以与 top、right、bottom 和 left 属性结合使用,将元素放置在您想要的位置。以下是位置属性的可能值 -

  • static − 元素框作为正常文档流的一部分进行布局,跟随前面的元素和后面的元素。

  • relative - 元素的盒子被布局为正常流的一部分,然后偏移一定距离。

  • absolute − 元素的框相对于其包含块进行布局,并且完全从文档的正常流程中移除。

  • fixed − 元素框是绝对定位的,具有position: absolute的行为描述。主要区别在于固定定位元素的包含块始终是视口。

现在让我们看一个使用position属性在div中垂直对齐元素的示例−

Example

的中文翻译为:

示例

<!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 - 元素中行的实际高度是该值乘以元素的字体大小。

  • length − 元素中行的高度是给定的值。

  • 百分比 − 元素中行的高度是根据元素的字体大小的百分比计算的。

让我们现在看一个使用line-height属性在div中垂直对齐元素的示例 -

Example

的中文翻译为:

示例

<!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 中的元素的示例 -

Example

的中文翻译为:

示例

<!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>