Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<div> with image has a bigger height than expected

Here is an HTML code to reproduce the problem:

<!DOCTYPE html>
<html>
    <body>
        <div style="width:800px; margin:0 auto;">
            <img src="logo.gif" width="100" height="40" />
        </div>
    </body>
</html>

When it is rendered in a desktop browser, the height of the only <div> becomes 45 pixels but not 40 as I expect (tested this in IE11 and Opera Next v20). logo.gif is 100x40, and the situation remains the same even if I apply zero border through CSS to the <img> tag (border, border-width, etc).

Why does it happen and how to fix it?

like image 345
TecMan Avatar asked Feb 12 '14 08:02

TecMan


1 Answers

I believe it is not a bug as it is rendered the same way in all major browsers. The problem is fixed if we set just the display:block style. Without this, the image is rendered as an inline element, and its bottom border is aligned to the so called text baseline.

Let's change our code to demonstrate this:

<!DOCTYPE html>
<html>
<body style="background-color: #FFFF99;">
<div style="width:800px; margin:0 auto; background-color: #00CCFF;">
<img src="logo.gif" width="100" height="40" style="border: 3px solid black;" />
Some text yyy qqq
</div>
</body>
</html>

The result is the following:

enter image description here

As you can see, the extra space is needed to render the text without clipping!


I found a confirmation of that in the well-known book by Eric Meyer CSS: The Definitive Guide - in the section dedicated to alignment, when it describes the {vertical-align: baseline} attribute for the <img> tag. Here is the corresponding excerpt:

This alignment rule is important because it causes some web browsers always to put a replaced element's bottom edge on the baseline, even if there is no other text in the line. For example, let's say you have an image in a table cell all by itself. The image may actually be on a baseline, but in some browsers, the space below the baseline causes a gap to appear beneath the image. Other browsers will "shrink-wrap" the image with the table cell and no gap will appear. The gap behavior is correct, according to the CSS Working Group, despite its lack of appeal to most authors.

like image 169
TecMan Avatar answered Nov 14 '22 22:11

TecMan