实现垂直居中

194 阅读1分钟

这个有很多种方法,搞懂属性之后其实可以写出来更多更方法。

子盒子不设置宽高
  1. 使用绝对定位+transform
.father{
  position:relative
  height:100px
  width:100px
}
.son{
  position:absolute
  top:50%
  left:50%
  transform:translate(-50%,-50%)
}
  1. 使用绝对定位+margin
.father{
  position:relative
  height:100px
  width:100px
}
.son{
  position:absolute
  top:0
  bottom:0
  left:0
  right:0
  margin:auto
}
子盒子设置宽高
  1. 使用绝对定位+calc
.father{
  position:relative
  height:100px
  width:100px
}
.son{
  position:absolute
  height:40px
  width:40px
  top:calc(50% - 20px)
  left:calc(50% - 20px)
}
  1. 使用绝对定位+负的margin
.father {
    position: relative;
}

.son {
    position: absolute;
    width:100px
    height:100px
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
}
使用弹性布局
.father{
  display:flex
  justify-content:center
  align-items:center
}
.son{
  height:40px
  width:40px
}
使用grid
.father{
  height:100px
  width:100px
  display:grid
  place-items:center
}
.son{
  height:40px
  width:40px
}
使用弹line-height

单纯的文字垂直水平居中

.father{
   height:100px
   line-height:100px
   width:100px
   text-align:center 
}