2015-06-19 145 views
0

我試圖創建一個響應垂直居中的燈箱,支持不同的圖像大小和控制相對定位到圖像,而無需使用JavaScript。垂直居中響應容器內部的響應式圖像

我得到它在Safari中的工作,但不幸的是,圖像並沒有在Firefox和Chrome中的高度方向擴展,它溢出了它的父項。

這裏的JSFiddle

這裏是我的代碼:

.overlay { 
 
    position:fixed; 
 
    top:0; 
 
    left:0; 
 
    right:0; 
 
    bottom:0; 
 
    background-color: rgba(0,0,0,.75); 
 
    text-align:center; 
 
    font-size:0; 
 
} 
 

 
.overlay:before { 
 
    content: ""; 
 
    display: inline-block; 
 
    vertical-align: middle; 
 
    height: 100%; 
 
} 
 

 
.container { 
 
    display:inline-block; 
 
    vertical-align:middle; 
 
    position:relative; 
 
    box-shadow:0 0 5px rgba(0,0,0,.5); 
 
    font-size:1rem; 
 
    max-width:80%; 
 
    max-height:80%; 
 
} 
 

 
.container img { 
 
    vertical-align: bottom; 
 
    max-width:100%; 
 
    max-height:100%; 
 
} 
 

 
.container .caption { 
 
    position:absolute; 
 
    bottom:0; 
 
    width:100%; 
 
    background-color:rgba(0,0,0,.5); 
 
} 
 

 
.container .prev, .container .next { 
 
    position:absolute; 
 
    top:50%; 
 
    -webkit-transform: translateY(-50%); 
 
    transform: translateY(-50%); 
 
} 
 

 
.container .prev { 
 
    left:0; 
 
} 
 

 
.container .next { 
 
    right:0; 
 
}
<div class="overlay"> 
 
    <div class="container"> 
 
     <img src="http://placehold.it/1920x1080" alt="" /> 
 
     <div class="caption">Some text...</div> 
 
     <a class="prev" href="#">Previous</a> 
 
     <a class="next" href="#">Next</a> 
 
    <div> 
 
</div>

它甚至有可能解決這個問題,而JavaScript的?

+0

你試過Flexbox的? –

+0

尚未,但可以工作。我會嘗試一下,謝謝! – sboesch

+0

請記住,Flexbox在IE上不起作用 –

回答

0

權,這裏有一個解決方案(作爲最好的,我可以從告訴你要完成什麼):

<div class='container'> 
    <img class='image' src='http://placehold.it/1920x1080'> 
</div> 

body, .container{ 
    position: absolute; 
    width: 100%; 
    height: 100%; 
    overflow:hidden; 
} 
.container { 
    top: 0; 
    left: 0; 
} 
.image { 
    position: absolute; 
    max-width: 80%; 
    max-height: 80%; 
    top: 50%; 
    left: 50%; 
    transform: translate(-50%, -50%); 
} 

fiddle

+0

感謝您的回答,但不幸的是,這不是我正在尋找的。我已經知道如何集中一個響應式圖像。我的問題是一個響應式容器中的圖像,其位置是:relative。我認爲這不存在任何CSS解決方案。 – sboesch