HTML+CSS 实现水平垂直居中

170 阅读1分钟

方法一:使用弹性布局(flex)

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="utf-8" />
    <title>垂直水平居中</title>
  </head>
  <style>
    body {
      margin: 0;
    }
    .father {
      display: flex;
      justify-content: center; /* 实现水平居中 */
      align-items: center; /* 实现垂直居中 */
      background: gray;
      height: 100vh;
    }
    .son {
      width: 80%;
      height: 60%;
      background: white;
    }
  </style>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>

方法二:使用transform

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>垂直水平居中-transform</title>
  </head>
  <style>
    body {
      margin: 0;
    }
    .father {
      position: relative;

      height: 100vh;
      background: gray;
    }
    .son {
      position: absolute; /* 子元素相对于父元素定位 */

      background: white;
      width: 50%;
      height: 50%;

      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  </style>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>

方法三:使用position和margin

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="utf-8" />
    <title>垂直水平居中-position+margin</title>
  </head>
  <style>
    body {
      margin: 0;
    }
    .father {
      background: gray;
      position: fixed;

      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
    }
    .son {
      width: 50%;
      height: 50%;
      background: white;
      margin: auto;
      position: fixed;

      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
    }
  </style>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>

方法四:使用table

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="utf-8" />
    <title>垂直水平居中-table</title>
    <style>
      /*** table-cell middle center组合使用 ***/
      body {
        margin: 0;
        padding: 0;
      }
      .father {
        height: 100vh;
        width: 100%;
        display: table;
        border: 5px solid red;
      }
      .son {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
        background-color: white;
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="son">您好</div>
    </div>
  </body>
</html>