A有一个图像,并希望能够在固定大小的可滚动区域中放大/缩小它。这很容易,但如果图像小于可滚动区域,则应该在垂直和水平方向上居中。我找不到一个解决办法,如何把它在中间垂直对齐。流行的解决方案,如垂直对齐一个div内的图像与响应的高度,或如何垂直居中一个div为所有浏览器?不工作,因为可滚动区域。
http://jsfidle.net/smvyadnv/9/
HTML
<div class="outer">
<div class="inner small">
<img src="http://lorempixel.com/g/500/300/nature/"></img>
</div>
</div>
<div class="outer">
<div class="inner large">
<img src="http://lorempixel.com/g/500/300/nature/"></img>
</div>
</div>
CSS
img {
width: 100%;
}
.outer {
height: 300px;
width: 400px;
overflow: scroll;
text-align: center;
}
.inner {
display: inline-block;
}
.inner.small {
width: 250px;
height: 150px;
}
.inner.large {
width: 500px;
height: 300px;
}
您不应该尝试将图像居中,而应该将.inner
元素居中。
您可以使用以下垂直/水平居中技术(摘自CSS技巧-CSS中的居中:完整指南)来实现这一点:
.outer {
...
position: relative;
...
}
.inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
因此您的代码如下所示:
img {
width: 100%;
}
.outer {
height: 300px;
width: 400px;
overflow: scroll;
position: relative;
}
.inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.inner.small {
width: 250px;
height: 150px;
}
.inner.large {
width: 500px;
height: 300px;
}
<div class="outer">
<div class="inner small">
<img src="http://lorempixel.com/g/500/300/nature/"></img>
</div>
</div>
<div class="outer">
<div class="inner large">
<img src="http://lorempixel.com/g/500/300/nature/"></img>
</div>
</div>
我只是给了您的inner small
图像一个名为cent
(中心)的id,并给了它下面的css,使它看起来像是在中心。
#cent{
padding-top:50px;
}
更新小提琴:http://jsfidle.net/smvyadnv/5/
如果你在找别的东西,请告诉我