html - 在可滚动的 div 中水平和垂直对齐图像

标签 html css

A 有一张图片,希望能够在固定大小的可滚动区域中放大/缩小它。这很容易,但是如果图像小于可滚动区域,则它应该在垂直和水平方向上都居中。我找不到如何将它垂直对齐在中间的解决方案。流行的解决方案,如 Vertically align an image inside a div with responsive heightHow 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/

相关文章:

html - 当我在元标记内容 ="max-width=1200px;"中定义时媒体查询是如何工作的

asp.net - 更改货币文本中美分样式的简便方法

javascript - 尽管添加了内容,如何使我的 div 保持相同的大小?

html - 我可以强制文本打印为白色吗?

javascript - HTML5 编辑器(contentEditable),带有类似 Google Docs 的页面

html - IndexedDB onversionchange 事件未在 Chrome 中触发

jquery 移动主题缩放

javascript - 如何将一个类添加到以前的 div

php - 无法连接数据库和处理 POST 请求

html - 在 'li' 中垂直对齐 'ul' 中间