2012-09-04 12 views
6

historia corta:¿Por qué las imágenes se centran verticalmente con `line-height` posicionado 2 píxeles debajo de donde deberían estar?

jsfiddle here. El comportamiento es sistemáticamente incorrecto en Chrome 21, Firefox 15 e IE9, lo que me hace pensar que estoy malinterpretando algo sobre las especificaciones de CSS. historia

más larga:

quiero centrar una imagen verticalmente mediante línea de altura. Establecí la altura del contenedor de la imagen igual a la altura de la línea, he restablecido los márgenes, los rellenos y los bordes de todos los elementos, pero la imagen está 2 píxeles por debajo de donde debería estar. Esto sucede tanto si la imagen es más pequeña que el contenedor, o más grande que (en cuyo caso usé max-width: 100; max-height: 100% para ajustar el tamaño).

La imagen tiene un número par de píxeles en ambos casos. No me interesaría mucho por imágenes más pequeñas que el contenedor, pero para las imágenes que son más grandes, una línea de 2 píxeles del fondo del contenedor sangrará en la parte superior de la imagen.

<!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

¿Has probado tus varias combinaciones sin la regla "vertical-align: middle"? – moopet

+0

Problema común con la imagen en línea que nunca me interesó buscar si hay algo en la especificación al respecto. Por lo general, puedo omitir el problema configurando la imagen para mostrar el bloque y establecer un margen: 0 auto ;. Pero este método no le permite tener una alineación vertical fluida (solo si conoce las medidas de altura). http://jsfiddle.net/8UaUQ/ –

Respuesta

5

usted tiene que fijar cero font-size para contenedores div elementos. Como las imágenes se muestran como elementos en línea, se ven afectadas por el texto en el contenedor div. Cero font-size reparar este problema:

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

Aquí es violín: http://jsfiddle.net/bZBsR/

Cuestiones relacionadas