2015-06-19 81 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