CSS 居中

transform

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <style>
    #parent {
      width: 500px;
      height: 500px;
      background: lightgray;
      position: relative;
  }
    #child {
      background: white;
      width: 250px;
      height: 250px;
      position: absolute;
      top: 50%;
      transform: translate(50%, -50%);
    }
  </style>
</head>
<body>
  <div id="parent">
      <div id="child"></div>
  </div>
</body>
</html>

felx

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <style>
    #parent {
      width: 500px;
      height: 500px;
      background: lightgray;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    #child {
      background: white;
      width: 250px;
      height: 250px;
    }
  </style>
</head>
<body>
  <div id="parent">
      <div id="child"></div>
  </div>
</body>
</html>

相关推荐