Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML forcing img dimensions requires block?

Tags:

html

css

I have a situation where I would like an HTML img which has not yet loaded to have a pre-set height. The reason is that this height will be used in a calculation that may fire before the image is fully loaded and needs to remain accurate. I tried the following:

<div>hello<img src='http://example.com/invalid.gif' class="testimage"> there</div>

and put in some css

.testimage {
    height: 200px;
    width: 200px;
}
​

and at least in Firefox 5, the extra space is not rendered (and oddly, the broken image doesn't show either, just a blank space). That is, until I add display: inline-block. In at least some other browsers the default display of inline produces the desired result. Is this expected? If so, why?

Here's a jsFiddle as well: http://jsfiddle.net/uYXD4/

like image 698
Dan Avatar asked Jun 25 '12 16:06

Dan


2 Answers

it says here that images are inline elements - http://htmlhelp.com/reference/html40/special/img.html

On the other hand take a look here - Is <img> element block level or inline level?

It looks like the <img> element is kind of both inline and block. No strict rules defining it, so probably the browser vendors make their own decisions about the defaults. So your best bet is to reset their assumptions to display: inline-block

like image 108
Zoltan Toth Avatar answered Oct 19 '22 02:10

Zoltan Toth


Images are replaced elements:

An element whose content is outside the scope of the CSS formatting model, such as an image, embedded document, or applet. For example, the content of the HTML IMG element is often replaced by the image that its "src" attribute designates.

For replaced elements, display: inline-block is supposed to have the same exact same efffect as display: inline, which is the default.

So this may be a possible explanation for that strange behaviour in some browsers*:

They treat only completely loaded images as replaced elements, and otherwise treat them as non-replaced elements. That makes sense after all, and the standard does not explicitly disallow that. As a consequence, there's 3 possible scenarios:

  1. replaced element, inline or inline-block doesn't matter, height property works
  2. inline non-replaced element, height attribute has no effect
  3. inline-block non-replaced element, height property works

Loaded images always qualify as 1., and broken/loading images may qualify as 1. or 2. (or 3. if you set display: inline-block explicitly)

*Not sure if that's how things actually work though.

like image 42
user123444555621 Avatar answered Oct 19 '22 03:10

user123444555621