记学习垂直水平居中的方法

100 阅读1分钟

前言:总是会被问到,垂直水平居中怎么实现,吧啦吧啦只会说一两种,今天就来总结总结下。

以此为基础


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>垂直居中</title>
  <style>
    .outer {
      width: 300px;
      height: 200px;
      border: 1px solid black;
    }

    .inner {
      width: 100px;
      height: 100px;
      border: 1px solid red;
    }
  </style>
</head>
<body>
<div class="outer">
  <div class="inner"></div>
</div>
</body>
</html>

就长这样

image.png

1. 使用定位 + translate偏移

<style>
    .outer {
      width: 300px;
      height: 200px;
      border: 1px solid black;
      position: relative;
    }

    .inner {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
</style>

2. 定位 + 0偏移量 + margin

<style>
    .outer {
      width: 300px;
      height: 200px;
      border: 1px solid black;
      position: relative;
    }

    .inner {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
    }
</style>

3. 定位 + 负margin

<style>
    .outer {
      width: 300px;
      height: 200px;
      border: 1px solid black;
      position: relative;
    }

    .inner {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      position: absolute;
      left: 50%;
      top: 50%;
      margin-left: -50px; /* 盒子宽度的一半 */
      margin-top: -50px; /* 盒子高度的一半 */
    }
</style>

4. table-cell

<style>
    .outer {
      width: 300px;
      height: 200px;
      border: 1px solid black;
      display: table-cell; /* 父元素display设置为table-cell */
      vertical-align: middle; /* 垂直居中 */
      text-align: center; /* 水平居中 */
    }

    .inner {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      display: inline-block; /* 子元素display设置为inline-block */
    }
</style>

5. table-cell + margin

<style>
    .outer {
      width: 300px;
      height: 200px;
      border: 1px solid black;
      display: table-cell; /* 父元素display设置为table-cell */
      vertical-align: middle; 
    }

    .inner {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      margin : 0 auto;
    }
</style>

7. flex

<style>
    .outer {
      width: 300px;
      height: 200px;
      border: 1px solid black;
      display: flex;
      align-items: center;
      justify-content: center;

    }

    .inner {
      width: 100px;
      height: 100px;
      border: 1px solid red;
    }
</style>

over。