CSS | 水平居中及垂直居中

147 阅读1分钟

Referrence: css-tricks.com/centering-c…

一、水平居中

  1. 对于行内元素

    .container {
        text-align: center;
    }
    
  2. 对于块级元素

    .self {
        margin: 0 auto;
    }
    

二、垂直居中

  1. 对于行内元素

    单行:

    .container {
        line-height: 100% | 父级块高度;
    }
    

    多行:

    flex image.png

  2. 对于块级元素

    (1)flex

    (2)绝对定位

    .child {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }
    
    .child {
        position: absolute;
        top: 0;
        bottom: 0;
        margin: auto;
    }
    

三、五种垂直水平居中方案

  1. 绝对定位

    .container{
      border: 1px solid black;
      width: 300px;
      height: 300px;
      position: relative;
    }
    
    .inner{
      width: 100px;
      height: 100px;
      background-color: pink;
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
    }
    
    .container{
      border: 1px solid black;
      width: 300px;
      height: 300px;
      position: relative;
    }
    
    .inner{
      width: 100px;
      height: 100px;
      background-color: pink;
      position: absolute;
      left: 50%;
      top: 50%;
      margin-top: -50px;
      margin-left: -50px;
    }
    
    .container{
      border: 1px solid black;
      width: 300px;
      height: 300px;
      position: relative;
    }
    
    .inner{
      width: 100px;
      height: 100px;
      background-color: pink;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translateX(-50%) translateY(-50%);
    }
    
  2. flex

    .container{
      border: 1px solid black;
      width: 300px;
      height: 300px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .inner{
      width: 100px;
      height: 100px;
      background-color: pink;
    }
    
  3. grid

    .container{
      border: 1px solid black;
      width: 300px;
      height: 300px;
      display: grid;
    }
    
    .inner{
      width: 100px;
      height: 100px;
      background-color: pink;
      margin: auto;
    }