在div中使用padding-bottom来锁定比例的垂直对齐图像



我有一个div,使用padding-bottom:100%来锁定div的宽高比为1:1(为了响应的目的):

<div class="image-container">
</div>
css:

.image-container {
    width: 100%;
    height: 0;
    padding-bottom: 100%;
    background:yellow;
}

现在,我有一个图像在这个容器的宽度:100%。然而,图像停留在顶部,我不能在图像上使用vertical-align:middle。

有没有办法让这个图像垂直居中?JSFiddle: http://jsfiddle.net/g819gz2a/

不幸的是,我将需要这个工作不仅为ie9,但致命的ie8

您可以使用absolute定位执行以下操作:

JS小提琴

.container {
    width:300px;
}
.image-container {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 100%;
    background:yellow;
}
img {
    width:100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate3d(-50%, -50%, 0px);
}

旧浏览器:

JS小提琴

img {
    background: green;
    width:100%;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
}

最新更新