【问题标题】:horizontally & vertically centered Responsive image水平和垂直居中的响应式图像
【发布时间】:2014-08-09 00:19:31
【问题描述】:

我试图让图像在高度和宽度可变的 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;
}

【问题讨论】:

    标签: html css alignment


    【解决方案1】:

    我过去曾尝试过这个,我想出的唯一非 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 的背景颜色设置为黑色,以查看没有图像边缘的缩放。我使用了这些尺寸,因此您可以通过调整框架大小来测试它。

    【讨论】:

    • 这很好,但我需要图像不能放大,只有在较小的窗口上更小。它应该保持水平和垂直居中,就像在我的示例中一样。
    • 我又玩了一遍,并设法使用您的背景方法而不是图像组合了一个工作小提琴:jsfiddle.net/me2loveit2/ejbLp/11
    • 我还需要寻找其他解决方案。这仅适用于图像,不适用于视频或 Flash 等任何其他媒体。
    猜你喜欢
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多