Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 690
HappyDeveloper Avatar asked Nov 27 '22 11:11

HappyDeveloper


1 Answers

I'm also looking for the answer to this problem. With max-width, width= and height=, the browser has enough data that it should be able to leave the right amount of space for an image but it just doesn't seem to work that way.

I worked around this with a jQuery solution for now. It requires you to provide the width= and height= for your <img> tags.

CSS:

img { max-width: 100%; height: auto; }

HTML:

<img src="image.png" width="400" height="300" />

jQuery:

$('img').each(function() { 
    var aspect_ratio = $(this).attr('height') / $(this).attr('width') * 100;
    $(this).wrap('<div style="padding-bottom: ' + aspect_ratio + '%">');
});

This automatically applies the technique seen on: http://andmag.se/2012/10/responsive-images-how-to-prevent-reflow/

like image 176
Paul Pritchard Avatar answered Nov 29 '22 03:11

Paul Pritchard