HTML中div内容垂直居中显示-方法一:使用 flexbox 布局

时间:2024-01-21 06:57:09
<!DOCTYPE html>
<html>
  <head>
    <style>
      .container {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100vh; /* 设置容器高度为视窗高度,以便垂直居中显示 */
      }
    </style>
  </head>
  <body>
    <div class="container">
      <p>这是要垂直居中显示的内容</p>
    </div>
  </body>
</html>

在上述代码中,我们创建了一个具有 container 类名的 div 容器,并将其设置为 flex 布局。通过设置 align-items: centerjustify-content: center 属性,实现了垂直和水平方向上的居中对齐。同时,我们将容器的高度设置为视窗高度(height: 100vh),以确保容器占据整个视窗并垂直居中显示。