css 如何使一个盒子水平垂直居中

132 阅读1分钟

css 如何使一个盒子水平垂直居中

方法一、使用 flex 布局

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style>
      .father {
        width: 500px;
        height: 500px;
        background-color: brown;
+        display: flex;
+        justify-content: center;
+        align-items: center;
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: cadetblue;
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>

方法二、使用定位和 transform

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style>
      .father {
        width: 500px;
        height: 500px;
        background-color: chocolate;
        position: relative;
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: darkcyan;
        position: absolute;
        left: 50%;
        top: 50%;
+        transform: translate(-50%, -50%);
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>

方法三、使用定位和 magin

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style>
      .father {
        width: 500px;
        height: 500px;
        background-color: chocolate;
        position: relative;
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: darkcyan;
        position: absolute;
        left: 50%;
        top: 50%;
+        margin-top: -50px;
+        margin-left: -50px;
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>

方法四、使用 display:table-cell

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style>
      .father {
        width: 500px;
        height: 500px;
        background-color: chocolate;
+        display: table-cell;
+        vertical-align: middle;
      }
      .son {
        width: 100px;
        height: 100px;
        background-color: darkcyan;
+        margin: auto;
      }
    </style>
  </head>
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
</html>