CSS 垂直水平居中实现方案

177 阅读1分钟

CSS 垂直水平居中实现方案

元素大小确定

其实元素大小确定的情况下,这个问题就不是那么有技术含量了,我们可以通过计算和相对绝对布局来实现哦。除了计算外还有margin:auto这个天生为居中设置的值可以实现哦。

margin: auto

.parent {
  position: relative;
  width: 100px;
  height: 100px;
  background: black;
}
.son {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  width: 10px;
  height: 10px;
  background: red;
}

元素大小不定

flex

最简单的方案了吧。

.parent {
    display: flex;
    flex-direction: 
    // 水平居中
    justify-content: center; 
    // 垂直居中
    align-items: center;
}
.son {
    
}

transform

.parent {
    position: relative;
}
.son {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%)
}

table

.parent {
    display: table;
}
.son {
    display: table-cell;
    // 垂直居中
    vertical-align: middle;
    // 水平居中
    text-align: center;
}
.grandson{
    // 水平居中
    display: inline-block;
}