CSS and image layout

First of all, there's no reference in the current CSS 2.1 specifications to the layout used to display images. Images, in their essential form, are considered to be inline-block elements. This means that images can have a width, an height, borders, margins and padding but with few minor differences. In their default display role, images can only be affected by horizontal margins, for example. Usually a safe way to get more control over images is to turn them into block-level elements. By doing so, vertical margins are also allowed.

Technically speaking, an image is made up by replaced content, meaning that the actual content of an image is inserted in a web document by fetching an external resource. In that sense, an image behaves more like an object element and that explains why some W3C members proposed to remove the img element in favor of the object element.

In CSS, images can be handled either as inline-block elements (default) or as block elements. A good example of the former group are emoticons. This kind of images live inside a line of text. By default, their vertical alignment is baseline. Bear in mind, however, that they actually affect the overall height of a line. IE6 has an obtuse bug that makes it double the line height when that line contains an image. If you want to change the vertical alignment of such images, just write this:

img {vertical-align: middle;}

With this rule, images are now aligned with the middle line that intersects a line of text. Obviously the final effect depends on the font size and line height of the text. So if you have some text with a base font size of 12 pixels and an emoticon which is 10 pixels tall, everything should work just fine.

The latter group, instead, requires more attention. When you turn an image into a block-level element, all the rules of a block formatting context are then applied. A frequent question asked by many developers on the web is: "How can I adjust the dimensions of an image so that it fit the dimensions of its container?". Use percentages, like so:

img {
  display: block;
  width: 100%;
}

This technique works fine only if the intrinsic dimensions of the child image are equal to or greater than the actual dimensions of its parent element. So if you have a container which is 200 pixels wide and an image whose intrinsic width is 300 pixels, then everything will be ok. On the contrary, if the image is 100 pixels wide, then the image will be displayed distorted by the browser.

A field that would require some further investigation is when you try to turn images into something different from inline and block elements. For example, what happens to an image when it's displayed as a table cell? If I have more spare time in the future, I'll test that.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.