2013-11-22 40 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%); 
}