CSS实现垂直居中的几种方式

47 阅读1分钟

基础元素

<body>
    <div class="parent">
        <div class="children">small</div>
    </div>
</body>

基础样式

   .parent {
        width: 300px;
        height: 300px;
        background: black;
    }

    .children {
        background: red;
    }

初始样式

image.png

1. 给父级元素设置flex布局

   .parent {
        display: flex;
        align-items: center;
        justify-content: center;
    } 

image.png

2. 给子元素设置绝对定位

给子元素设置绝对定位,设置top: 50%, left: 50%, 并通过transform向自身宽度,高度的50%分别向左和向上偏移

.parent {
        position: relative;
    }

.children {
     background: red;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
  }

样式同上:

image.png

3. 父元素设置flex, 子元素设置margin: auto

.parent {
        display: flex;
    }

    .children {
        margin: auto;
    }

4. 子元素设置绝对定位,margin为auto;

这个方法需要设置子元素宽度和高度,不然会占满整个父级元素

.parent {
        position: relative;
    }

    .children {
        position: absolute;
        margin: auto;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        width: 100px;
        height: 100px;
    }

image.png