div中不同大小的img水平垂直居中

需求是在div中有一个img标签,在不知道图片大小的情况下始终需要图片在其父容器中水平垂直居中,如果图片小于容器大小就水平垂直居中显示,如果图片大于容器大小宽度,图片宽度100%且高度自适应出现滚动条即可:

<div class="box">
   <div class="img-wrap">
     <img class="img" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1548904156&di=a846993fd591aa3f7b70a78288861fae&imgtype=jpg&er=1&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201603%2F09%2F20160309192753_rnsLt.jpeg" alt="">
   </div>
 </div>

以前使用水平垂直居中我使用的方法都是这样:

<style>
   .box{
     width: 800px;
     height: 500px;
     margin: auto;
     background: rosybrown;
   }
   .img-wrap{
     width: 100%;
     height: 100%;
     overflow: auto;
     position: relative;
   }
   .img{
      max-width: 100%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
 </style>

这种方式在chrome下没问题,不管图片多大都会垂直居中,但是在IE下就会发现问题,即使是IE11,改进后的方法如下:

.img{
     max-width: 100%;
     margin: auto;
     position: absolute;
     top: 0;
     bottom: 0;
     left: 0;
     right: 0;
   }

此时,不论是在chrome还是IE下都可以实现不同尺寸图片水平垂直居中。

猜你喜欢

转载自blog.csdn.net/weixin_43443341/article/details/92783810