簡體   English   中英

水平和垂直居中的響應圖像

[英]horizontally & vertically centered Responsive image

我正在嘗試在可變高度和寬度的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解決方案(順便皺眉 )是這樣的:

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的背景色設置為黑色以查看沒有圖像邊緣的縮放比例。 我使用了這些尺寸,因此您可以通過調整框架的大小來對其進行測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM