Fluid Images: How to set width and height?


I'm trying to build a fluid layout, for which I am styling big images with:

.fluid_img {
  height: auto;
  width: auto;
  max-width: 100%;

This works fine, the problem is that I can no longer use the width and height attributes in the html img tag (they will have no effect). I need those attributes so the browser can "save" the space needed for the image before it has been loaded, so the rest of the page don't move when the image is loaded.

Is there any way to have both features? (fluid image + space saved before image load)

8/14/2011 7:43:00 AM

Accepted Answer

No, because you're setting the absolute dimensions in HTML. Those cannot change like your image will, so it's not realistic.

The most reasonable way I can think is to load the image into JavaScript. Then determine how large it has grown to "fit" into the fluid grid. Then you can apply these numbers as new width="" and height="" attributes in HTML. This is fairly roundabout, though. So I wouldn't recommend it!

I may be glossing over some other ideas so you may wish to check Google. But from your description I don't think you can have a fluid image with direct width/height attribs in HTML.

8/14/2011 4:41:00 PM

The other answers are plain incorrect. With the help CBroe I found a solution: https://stackoverflow.com/questions/15520623/browser-image-layouting-in-css-before-image-loaded-with-whole-width-and-proporti

Basically you make use of the fact that padding values given in percentage always are calculated based on the width of an element, even for padding-top/-bottom.

<div style="position:relative; width:100%; height:0; padding-top:50%;">
  <img style="position:absolute; top:0; left:0; width:100%;" src="…">

You need to calculate padding-top yourself beforehand and it represents the aspectio ratio of your image, basically: height/width*100. So you would need php or whatever scripting language you use to calculate this aspect ratio. Other than that it works like a charm an no javascript is necessary.