2013-11-22 35 views
14

搜索堆栈溢出和谷歌后,我仍然想知道如何垂直居中大于它的父元素的图像。我没有使用高度,只使用max-height,因为我想制作一个响应式解决方案,而不使用jQuery。如果可能的话。响应垂直中心与隐藏溢出

下面是一些代码:

<div style="max-height: 425px; overflow: hidden;"> 
    <img src="http://img.youtube.com/vi/jofNR_WkoCE/maxresdefault.jpg"> 
</div> 

回答

43

到中心垂直的更大的图像ü可以使用的建设和CSS波纹管

<div class="img-wrapper"> 
    <img src="http://img.youtube.com/vi/jofNR_WkoCE/maxresdefault.jpg"> 
</div> 

和css:

.img-wrapper{ 
    position: relative; 
    overflow:hidden; 
    height:425px; 
} 

.img-wrapper img{ 
    position: absolute; 
    top:-100%; left:0; right: 0; bottom:-100%; 
    margin: auto; 
} 

FIDDLE

+0

在webkit浏览器中表现出色!你可以让它在Firefox中工作吗? –

+0

@ExtPro其实这个解决方案没有使用任何Javascript,但只在webkit浏览器中工作正常 –

+5

找到了Firefox的一个小技巧。将顶部和底部更改为-100%。 http://jsfiddle.net/PRJHw/5/ –

0

尝试

<html> 
<head> 
</head> 
<body > 

    <div style="max-height: 425px;border:1px solid;max-width:500px;overflow:hidden"> 
     <img src="http://img.youtube.com/vi/jofNR_WkoCE/maxresdefault.jpg" style='position: relative;top: -231px;left: -500px;'> 
    </div> 
</body> 
</html> 
+0

使用像素的图像定位使得它无响应 –

0

如果你不需要使用img标签(fiddle):

CSS

.imageContainer { 
    margin: 0; 
    height: 200px; /* change it to your value*/ 
    width: 200px; /* or use fixed width*/ 
    background: transparent url('') no-repeat center; 
    overflow: hidden; 
} 

HTML

<div class="imageContainer" style="background-image: url('http://deepwish.com/site/wp-content/uploads/2013/10/butterfly2_large.jpg');"></div> 
+0

我想用它像一个图像(),而不是背景 –

+0

@Henrik Albrechtsson由于容器和/或图像(?)可能具有可变大小,因此您需要为此使用一些JS:orde r在CSS中计算的偏移量至少有一个必须是硬编码的,除非它在运行时计算(JS),除非图像被缩放 – SW4

+0

实际上[此解决方案](http://jsfiddle.net/PRJHw/2 )在没有使用任何Javascript的情况下工作正常,但只能在webkit浏览器中使用 –

-1

,如果你想使一个负责任的形象,尝试使用
<div style="">
<img src="http://img.youtube.com/vi/jofNR_WkoCE/maxresdefault.jpg" width="100%" height="100%">
</div>

+0

我想使用overflow hidden来从[image]中删除黑边(http://img.youtube.com/vi/jofNR_WkoCE/maxresdefault .jpg)以上 –

2

我找到了一种方法,使其与只max-height(而不是一个固定的高度)设置的容器上的工作。

坏消息是它需要一个额外的包装元素。

HTML:

<div class="img-wrapper"> 
    <div class="img-container"> 
     <img src="http://img.youtube.com/vi/jofNR_WkoCE/maxresdefault.jpg"> 
    </div> 
</div> 

CSS:

.img-wrapper { 
    overflow: hidden; 
    max-height: 425px; 
} 

.img-container { 
    max-height: inherit; 
    transform: translateY(50%); 
} 

.img-wrapper img { 
    display: block; 
    transform: translateY(-50%); 
}