如何使img或者div在div中水平垂直居中显示

闲来无事,被人问到如何使img在一个div中垂直居中显示,自己就总结了如下几种方法,供大家参考:

方法一:在box中添加span空元素

<div id="box">
  <div class="img"></div>
  <span></span>
</div>
 #box{
      width: 200px;
      height: 200px;
      background:black;
      margin:0 auto;
      text-align: center;
    }
    .img{
      width: 100px;
      height: 100px;
      background:white;
      display: inline-block;
      vertical-align: middle;
    }
    #box span{
      display: inline-block;
      width:0;
      height:100%;
      vertical-align: middle;
    }

方法二:使用定位法,使用定位法时,img包含两种情况:

(1)固定宽高

<div id="box">
  <div class="img"></div>
</div>
 #box{
      width: 200px;
      height: 200px;
      background:black;
      margin:0 auto;
      text-align: center;
      position: relative;
    }
.img{
      width: 100px;
      height: 100px;
      position: absolute;
      background: white;
      left:50%;
      top:50%;
      margin-top:-50px;
      margin-left:-50px;
    }

(2)无固定宽高

<div id="box">
  <div class="img"></div>
</div>
#box{
      width: 200px;
      height: 200px;
      background:black;
      margin:0 auto;
      text-align: center;
      position: relative;
    }
 .img{
      width: 100px;
      height: 100px;
      position: absolute;
      background: white;
      left:50%;
      top:50%;
      -webkit-transform: translate(-50%,-50%);
      -moz-transform:translate(-50%,-50%);
      -ms-transform: translate(-50%,-50%);
      -o-transform: translate(-50%,-50%);
      transform: translate(-50%,-50%);
    }
方法三:设置父div为table-cell属性

<div id="box">
  <div class="img"></div>
</div>
  #box{
      width: 200px;
      height: 200px;
      background:black;
      display: table-cell;
      text-align: center;
      vertical-align: middle;
    }
 .img{
      width: 100px;
      height:100px;
      background: white;
      display: inline-block;
    }

方法四:使用flex布局

<div id="box">
  <div class="img"></div>
</div>
#box{
  width: 200px;
  height: 200px;
  background:black;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  margin:0 auto;
}
.img{
      width: 100px;
      height:100px;
      background: white;
    }

前两种是在开发中用的比较多的,最后一种在移动端布局使经常使用,只限子元素只有一个元素的情况下,以上为本人的见解,如有错误还请大家指正!





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值