2012-09-04 30 views
6

短故事:爲什麼圖像垂直居中,'line-height`位於它們應該位於的下方2個像素處?

jsfiddle here。在Chrome 21,Firefox 15和IE9中,這種行爲一直是錯誤的,這讓我覺得我對CSS規範有些誤解。

更長的故事:

我要垂直居中的圖像使用的line-height。我已經設置圖像容器的高度等於行高,我已經重置了所有元素的邊距,填充和邊框,但圖像的位置應該低於2像素。無論圖像是小於容器還是大於容器(在這種情況下,我使用max-width: 100; max-height: 100%來縮小容器大小)。

在這兩種情況下,圖像都具有偶數個像素。對於比容器小的圖像,我不會太在意,但對於較大的圖像,來自容器背景的2像素線將在圖像頂部滲透。

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>Images centered vertically with line-height have center miscalculated by 2 pixels</title> 

    <style type="text/css"> 
     * { margin: 0; padding: 0; border: 0px solid cyan; } /* reset all margins, paddings and borders */ 
     html { 
      font-size: 16px; 
      line-height: normal; 
     } 
     body { 
      line-height: 100%; 
      background: gray; 
     } 
     .img-wrapper-center { 
      width: 400px; 
      height: 200px; /* necessary, besides line-height, if images are taller than it */ 
      line-height: 200px; /* must be equal to line-height */ 
      text-align: center; 
      background: white; 
     } 
     .img-wrapper-center img { 
      vertical-align: middle; 
      /* Comment the two rules below. The first image will still be mis-aligned by two pixels, but the second will not. */ 
      max-width: 100%; max-height: 100%; /* force scaling down large images */ 
     } 

    </style> 
</head> 

<body> 

    <div class="img-wrapper-center" id="div1"> 
     <img src="http://gravatar.com/avatar" id="img1"/> <!-- 80x80 --> 
    </div> 

    <div class="img-wrapper-center" id="div2" style="background: green"> 
     <img src="http://www.w3.org/html/logo/img/class-header-semantics.jpg" id="img2" /> <!-- 495x370 --> 
    </div> 

    <p> 
    Note how the second image is misaligned down by two pixels. 
    The first one is mis-aligned the same way. Sizes and coordinates are below. 
    </p> 

    <script> 
     document.writeln('div1 top: ' + document.getElementById('div1').offsetTop + '<br/>'); 
     document.writeln('image 1 height: ' + document.getElementById('img1').offsetHeight + '<br/>'); 
     document.writeln('div1 height: ' + (document.getElementById('div1').offsetHeight) + '<br/>'); 
     document.writeln('image 1 top should be at: ' + (document.getElementById('div1').offsetHeight - document.getElementById('img1').height)/2 + '<br/>'); 
     document.writeln('image 1 top actually is at: ' + document.getElementById('img1').offsetTop + '<br/>'); 
     document.writeln('div2 top: ' + document.getElementById('div2').offsetTop + '<br/>'); 
     document.writeln('img2 top: ' + document.getElementById('img2').offsetTop + '<br/>'); 
    </script> 

</body> 
</html> 
+0

您是否嘗試過不使用「vertical-align:middle」規則的各種組合? – moopet

+0

內聯圖像的常見問題,如果在規範中有關於它的內容,我從不在意。通常我可以通過將圖像設置爲顯示塊並設置邊距來繞過問題:0 auto ;.但是這種方法不允許你有一個流體的垂直排列(只有當你知道高度測量時)。 http://jsfiddle.net/8UaUQ/ –

回答

5

您必須爲容器div設置零font-size元素。 由於圖像顯示爲內嵌元素,因此它們受容器div中文本的影響。零個font-size修復了這個:

.img-wrapper-center 
{ 
    font-size:0; 
} 

這裏是提琴:http://jsfiddle.net/bZBsR/