CSS四种方式实现垂直居中

82 阅读1分钟
  1. margin-top -50%
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>index/title>
  <style>
    .parent{
      height: 600px;
      border: 1px solid red;
      position: relative;
    }
    .child{
      border: 1px solid green;
      width: 300px;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -150px;
      height: 100px;
      margin-top: -50px;
    }
  </style>
</head>
<body>
  <div class="parent">
    <div class="child">
      一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
    </div>
  </div>
</body>
</html>
  1. translate -50%
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>index/title>
  <style>
    .parent{
      height: 600px;
      border: 1px solid red;
      position: relative;
    }
    .child{
      border: 1px solid green;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }
  </style>
</head>
<body>
  <div class="parent">
    <div class="child">
      一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
    </div>
  </div>
</body>
</html>
  1. absolute margin auto
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>index/title>
  <style>
    .parent{
      height: 600px;
      border: 1px solid red;
      position: relative;
    }
    .child{
      border: 1px solid green;
      position: absolute;
      width: 300px;
      height: 200px;
      margin: auto;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
    }
  </style>
</head>
<body>
  <div class="parent">
    <div class="child">
      一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
    </div>
  </div>
</body>
</html>
  1. flex
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>index/title>
  <style>
    .parent{
      height: 600px;
      border: 3px solid red;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .child{
      border: 3px solid green;
      width: 300px;
    }
  </style>
</head>
<body>
   <div class="parent">
    <div class="child">
      一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
    </div>
  </div>
</body>
</html>