Dynamic aspect-ratio to images via JavaScript jQuery

I would like to add aspect ratio as inline CSS for images via JavaScript (or jQuery) to avoid content reflow while using lazy-loading js. It should add an inline aspect ratio according to the image attributes aspect-ratio: attr(width) / attr(height). It should apply only when there’s a height and width attribute.

1 Like

As far as I know modern browsers will allocate the image space based on the width and height attributes in the image itself. Therefore (theoretically) all you have to do is ensure the natural dimensions of the image are supplied in the img attribute (as you should do for all images even if css is resizing them later).

Update! Times changed fast here, and to avoid lazy-load jank, all you have to do is put the correct natural width and height attributes on images and they will load nicely, even if CSS makes the image fluid with. So do it like: <img src="image.jpg" width="800" height="600">

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.