CSS中的垂直居中总结

172 阅读1分钟

1 垂直居中总结

效果预览:

图片垂直居中.png

1.1 使用 flex 布局完成垂直居中

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .container {
      width: 300px;
      height: 300px;
      margin-left: 300px;
      border: 1px solid #f00;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .img_box {
      width: 200px;
      height: 200px;
    }
    .img_box > img {
      width: 200px;
      height: 200px;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="img_box">
      <img src="./images/alsj.webp" alt="">
    </div>
  </div>
</body>
</html>

1.2 Display: table 完成水平垂直居中

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .container {
      width: 300px;
      height: 300px;
      margin-left: 300px;
      border: 1px solid #f00;
      display: table;
    }
    .img_box {
      width: 200px;
      height: 200px;
      display: table-cell; 
      vertical-align: middle;
      text-align: center;
    }
    .img_box > img {
      width: 200px;
      height: 200px;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="img_box">
      <img src="./images/alsj.webp" alt="">
    </div>
  </div>
</body>
</html>

1.3 用绝对定位完成水平垂直居中(兼容性好)

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .container {
      width: 300px;
      height: 300px;
      margin-left: 300px;
      border: 1px solid #f00;
      position: relative;
    }
    .img_box {
      width: 200px;
      height: 200px;
      position: absolute;
      top: 50%;
      left: 50%; 
      transform: translate(-50%,-50%);
    }
    .img_box > img {
      width: 200px;
      height: 200px;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="img_box">
      <img src="./images/alsj.webp" alt="">
    </div>
  </div>
</body>
</html>

1.4 用 grid 布局完成水平垂直居中

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
      .container {
        width: 300px;
        height: 300px;
        margin-left: 300px;
        border: 1px solid #f00;
        display: grid;
        place-items: center;
      }
      .img_box {
        width: 200px;
        height: 200px;
      }
      .img_box > img {
        width: 200px;
        height: 200px;
      }
  </style>
</head>
<body>
  <div class="container">
    <div class="img_box">
      <img src="./images/alsj.webp" alt="">
    </div>
  </div>
</body>
</html>

1.5 单行文本的水平垂直居中

单行文本的水平垂直居中除了使用 flex 或 grid 布局实现外,还可以使用行高 line-height 来实现,效果如下:

单行文本水平垂直居中.png

代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
      .container {
        width: 300px;
        height: 300px;
        margin-left: 300px;
        border: 1px solid #f00;
​
      }
      .container p {
        border: 1px solid #0f0;
        height: 40px;
        line-height: 40px;  
        text-align: center;
      }
  </style>
</head>
<body>
    <div class="container">
        <p>我是单行文本</p>
    </div>
</body>
</html>