元素垂直居中的常见方法

    
  <--HTML-->
  <div class="box box1"> <div>flex</div> </div> <div class="box box2"> <div>inline-block</div> </div> <div class="box box3"> <div>position</div> </div> <div class="box box4"> <div class="cell"> <div>table</div> </div> </div> <div class="box box5"> <div>position+0</div> </div>

公共样式:

.box {
  width: 500px;
  height: 100px;
  background: lightblue;
  margin-bottom: 10px;
}
.box > div {
  width: 100px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  background: pink;
}

1.display:flex: 

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

2.将元素设置为内联块再设置父元素的行高:

.box2 {
  line-height: 100px;
  text-align: center;
}
.box2 > div {
  display: inline-block;
}

3.使用position定位:

.box3 {
  position: relative;
}
.box3 > div {
  position: absolute;
  top: calc(50% - 25px);
  left: calc(50% - 50px);
}

4.给元素添加一个包裹层将元素设置为inline-block,包裹层设置为table-cell

.box4 {
  display: table;
  vertical-align: middle;
}
.box4 .cell {
  display: table-cell;
  background: lightblue;
  vertical-align: middle;
  text-align: center;
}
.box4 .cell > div {
  display: inline-block;
  background: pink;
  width: 100px;
  height: 50px;
}

5.还是使用position但是将top、left、right、bottom都设为0

.box5 {
  position: relative;
}
.box5 > div {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

在这几种方法中,当元素宽高改变时:

可以看出使用flex、table-cell、position+0这三种方法实现的结果依然是垂直居中,所以在元素宽高未知的情况下想要居中可以使用这三种方法。

转载于:https://www.cnblogs.com/cjw-ryh/p/7747387.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值