Skip to content

垂直居中

⽔平居中

行内元素

  1. 设置⽗元素 text-align:center

块级元素,定宽

  1. margin :margin: auto

  2. 绝对定位

    css
    .parent {
      position: relative;
    }
    
    .child {
      position: absolute;
      left: 50%;
      width: 100px;
      margin-left: -50px;
      /* 自身宽度的一半 */
    }
    
    /* 可简写 */
    .child {
      position: absolute;
      left: calc(50% - 50px);
      width: 100px;
    }

块级元素,不定宽

  1. 绝对定位 + translate

    css
    .parent {
      position: relative;
    }
    
    .child {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
  2. flex

    css
    .parent {
      display: flex;
      justify-content: center;
    }
    
    /* 下面这种也行 */
    .parent {
      display: flex;
      margin: auto;
    }

垂直居中

定高

  1. 绝对定位

    css
    .parent {
      position: relative;
    }
    
    .child {
      position: absolute;
      top: 50%;
      height: 100px;
      margin-top: -50px;
    }
    
    /* 可简写 */
    .child {
      position: absolute;
      top: calc(50% - 50px);
      height: 100px;
    }
  2. margin

    css
    .parent {
      position: relative;
    }
    
    .child {
      position: absolute;
      top: 0;
      bottom: 0;
      height: 100px;
      margin: auto;
    }

不定高

  1. 父级使用 table-cell 布局,指定 vertical-align 属性为 middle

  2. 绝对定位 + translate

    css
    .parent {
      position: relative;
    }
    
    .child {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
  3. flex

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

垂直水平居中

定宽定高

  1. 绝对定位 + top、left、right、bottom都为0 + margin:auto
css
.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: 100px;
  height: 100px;
  margin: auto
}
  1. 绝对定位 + top、left50% + margin各自的一半
css
.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 100px;
  margin-left: -50px;
  margin-top: -50px;
}

/* 可简写 */
.child {
  position: absolute;
  top: calc(50% - 50px);
  left: calc(50% - 50px);
  width: 100px;
  height: 100px;
}

不定宽高

  1. 绝对定位+ top、left50% + translate(-50%, -50%)
css
.parent {
  position: relative;
  width: 300px;
  height: 300px;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 100px;
  transform: translate(-50%, -50%);
}
  1. table-cell
css
.parent {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

.child {
  display: inline-block;
}
  1. flex
css
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
  1. grid
css
.parent {
  display: grid;
  justify-self: center;
  align-self: center;
}