css水平垂直居中

67 阅读1分钟

要实现水平居中布局,可以使用以下几种方法:

  1. 使用Flex布局:
<!DOCTYPE html>
<html>
<head>
  <title>水平居中布局 - Flex布局</title>
  <style>
    .container {
      display: flex;
      justify-content: center; /* 水平居中 */
      align-items: center; /* 垂直居中 */
      height: 100vh; /* 设置容器高度,以便垂直居中生效 */
    }
  </style>
</head>
<body>
  <div class="container">
    <!-- 居中内容 -->
    <p>居中内容</p>
  </div>
</body>
</html>
  1. 使用绝对定位和transform:
<!DOCTYPE html>
<html>
<head>
  <title>水平居中布局 - 绝对定位和transform</title>
  <style>
    .container {
      position: relative; /* 定位参照的父容器 */
      height: 100vh; /* 设置容器高度,以便垂直居中生效 */
    }
    
    .centered-content {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%); /* 水平和垂直居中 */
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="centered-content">
      <!-- 居中内容 -->
      <p>居中内容</p>
    </div>
  </div>
</body>
</html>
  1. 使用text-align属性(适用于行内元素):
<!DOCTYPE html>
<html>
<head>
  <title>水平居中布局 - text-align</title>
  <style>
    .container {
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="container">
    <!-- 居中内容 -->
    <p style="display: inline-block;">居中内容</p>
  </div>
</body>
</html>

这些方法都可以实现水平居中布局,您可以根据具体的需求选择其中一种来实现水平居中效果。