图片居中方法

Table of Contents

很多时候都需要用到图片居中,这里简单记录一下。

JavaScript 方法

获取图片宽高进行计算。

CSS 方法

<style>
  .box {
    width: 100px;
    height: 100px;
    display: table-cell;
    vertical-align: middle;
    border: 1px solid gray;
  }
  .box img {
    max-width: 100%;
    max-height: 100%;
    vertical-align: middle;
  }
</style>

或者:

<style>
  .box {
    width: 100px;
    height: 100px;
    text-align: center;
    border: 1px solid gray;
  }
  .box img {
    max-width: 100%;
    max-height: 100%;
    margin-top: 50%;
    transform: translateY(-50%);
  }
</style>

IE 兼容

在 ie 下面,图片的 max-width 或 max-height 会有问题。浏览器会根据图片的宽高调整父元素的宽高,之后再设置图片的宽高,结果就是 max-width 和 max-height 是相对于图片本身的大小,而不是父盒子。目前 ie11 的解决方法是给父盒子也设置 max-width 和 max-height ,值就是父盒子的宽高。

<style>
  .box {
    width: 100px;
    height: 100px;
    max-width: 100px;
    max-height: 100px;
    text-align: center;
    border: 1px solid gray;
  }
  .box img {
    max-width: 100%;
    max-height: 100%;
    width: auto;
    height: auto;
    margin-top: 50%;
    transform: translateY(-50%);
  }
</style>

或者直接添加 line-height 属性。

ie10 按照上面的设置会出现图片无法等比显示的问题。

文章最初发布在简书,时间为 2018.07.01 22:31。

链接:https://www.jianshu.com/p/edf17687c89b