html - 水平和垂直居中的响应图像

标签 html css alignment

我正在尝试让图像在高度和宽度可变的 div 中水平和垂直居中。 到目前为止,一切顺利。(请参阅下面的 jsfiddle 链接)

现在要注意的是,如果容器的高度和/或宽度小于图像的高度或宽度,图像也应该响应并进行调整。

在研究、浏览所有不同的“解决方案”并寻找解决方案之后,我无法找到完美的解决方案,但有两个接近:

1.)除了当窗口宽度小于图像宽度,图像不再水平对齐时,第一个完成了我需要的一切:

http://jsfiddle.net/me2loveit2/ejbLp/8/

HTML

<div class="overlay">
    <div class="helper"></div>
    <img src="http://dummyimage.com/550x480/000/fff?text=H/V Centered and height/width variable">
</div>

CSS

.helper {
    height:50%;
    width:100%;
    margin-bottom:-240px;
    min-height: 240px;
}
.overlay {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0px;
    left: 0px;
    cursor: pointer;
    background-color: rgba(0, 0, 0, 0.5);
}
img {
    margin: 0 auto;
    max-width: 100%;
    max-height: 100%;
    display: block;
}

2.) 第二个示例保持所有内容对齐,但当高度小于图像高度时图像不会缩小:

http://jsfiddle.net/me2loveit2/ejbLp/9/

HTML

<div id="outer">
    <div id="container">
        <img src="http://dummyimage.com/550x480/000/fff?text=H/V Centered and height/width variable">
    </div>
</div>

CSS

#outer {
    height:100%;
    width:100%;
    display:table;
    position:fixed;
    top:0px;
    left:0px;
    background-color: rgba(0, 0, 0, 0.5);
}
#container {
    vertical-align:middle;
    display:table-cell;
    max-width: 100%;
    max-height: 100%;
}
img {
    margin: 0 auto;
    max-width: 100%;
    max-height: 100%;
    display:block;
}

最佳答案

我过去曾尝试过这个,我想出的唯一非 JS 解决方案(顺便说一下,这是 frowned upon )是这样的:

html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}

body {
    display: table;
}

.container {
    display: table-cell;
    vertical-align: middle;
    border: 1px solid #f00;
}

.container > div {
    width: 100%;
    height: 100%;
    margin: 0 auto;
    border: 1px solid #00f;
    max-width: 550px;
    max-height: 480px;
    background: url("http://dummyimage.com/550x480/000/fff?text=H/V Centered and height/width variable") 50% 50% no-repeat;
    background-size: contain;
}

<div class="container"><div></div></div>

http://jsfiddle.net/pYzBf/1/

div 的背景颜色设置为黑色以查看没有图像边缘的缩放。我使用了这些尺寸,因此您可以通过调整框架大小来测试它。

关于html - 水平和垂直居中的响应图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24290032/

相关文章:

javascript - 动态添加点击事件到按钮

javascript - 我可以将 required 属性应用于 HTML5 中的 <select> 字段吗?

html - 表单输入和按钮没有完全对齐

HTML5 CSS 流式布局问题

javascript - css 和 js 文件在 php 中不起作用

html - 如何将此响应式图像垂直和水平居中?

html - 文本未在我的 li 中居中

jquery - Bootstrap Gallery 空白区域

javascript - 编码 HTML 和 JavaScript

javascript - 更改导航栏高度时内容下推页面