A 有一张图片,希望能够在固定大小的可滚动区域中放大/缩小它。这很容易,但是如果图像小于可滚动区域,则它应该在垂直和水平方向上都居中。我找不到如何将它垂直对齐在中间的解决方案。流行的解决方案,如 Vertically align an image inside a div with responsive height或 How to vertically center a div for all browsers?由于可滚动区域而不起作用。
http://jsfiddle.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 Tricks - Centering in CSS: A Complete Guide )实现此目的:
.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>
关于html - 在可滚动的 div 中水平和垂直对齐图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28494783/