参考资料

  1. 如何添加按钮的过渡动画效果?
  2. display: flex/inline-flex示例
  3. css颜色属性详细说明以及案例
  4. 使用CSS Grid和Flexbox两种现代布局方式实现4列12个产品布局的方法
  5. 目标伪类选择器详细说明以及案例
  6. css div居中代码
  7. 哪种布局方式更适合移动端?
  8. align-self: auto/stretch详细说明

水平居中

  1. 行内元素

    .parent {
      text-align: center;
    }
  2. 块级元素(固定宽度)

    .child {
      width: 200px;
      margin: 0 auto;
    }
  3. Flexbox

    .parent {
      display: flex;
      justify-content: center;
    }
  4. Grid

    .parent {
      display: grid;
      place-items: center;
    }

垂直居中

  1. 单行文本

    .parent {
      height: 100px;
      line-height: 100px;
    }
  2. Flexbox

    .parent {
      display: flex;
      align-items: center;
    }
  3. Grid

    .parent {
      display: grid;
      place-items: center;
    }
  4. 绝对定位(已知高度)

    .child {
      position: absolute;
      top: 50%;
      height: 100px;
      margin-top: -50px; /* 高度的一半 */
    }

水平垂直居中

  1. Flexbox

    .parent {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  2. Grid

    .parent {
      display: grid;
      place-items: center;
    }
  3. 绝对定位 + transform

    .child {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

示例代码

<!DOCTYPE html>
<html>
<head>
  <style>
    /* 水平居中 */
    .center-h {
      width: 200px;
      margin: 0 auto;
      background: lightblue;
      text-align: center;
    }

    /* 垂直居中 */
    .container-v {
      height: 200px;
      display: flex;
      align-items: center;
      background: lightgray;
    }

    /* 水平垂直居中 */
    .container-hv {
      height: 300px;
      display: grid;
      place-items: center;
      background: lightgreen;
    }
    .box-hv {
      width: 150px;
      height: 100px;
      background: coral;
    }
  </style>
</head>
<body>
  <div class="center-h">水平居中</div>

  <div class="container-v">
    <div>垂直居中</div>
  </div>

  <div class="container-hv">
    <div class="box-hv">水平垂直居中</div>
  </div>
</body>
</html>