Specifying image dimensions in HTML vs CSS for page loading
Asked Answered
S

2

9

I've learnt from somewhere a long time ago that specifying width and height for <img> elements in an HTML document speeds up and improves the page loading experience, and have generally kept to this practice:

<img src="" width="100" height="100" />

I'm now faced with a situation where I have a very large number of images on a single page, and I'd prefer to set the dimensions via CSS for both easier control and less repetitive HTML code:

.whatever img {width: 100px; height: 100px;}

Although this isn't a hugely serious issue, I'm wondering whether declaring the dimensions in CSS will have the same benefits as declaring the dimensions in HTML, or whether it ought to just be done in HTML directly?

Any insight would be welcome.

Thanks

Swingle answered 26/11, 2010 at 18:43 Comment(1)
flagged as a dupe of this (I prefer this question's phrasing though)Monteverdi
F
12

I guess if the style sheet is available immediately, the image dimensions will immediately apply to the layout, which is the whole point of the exercise.

That guess is supported by Google's pagespeed rules. They seem to be fine with specifying images that way (emphasis mine):

Specifying a width and height for all images allows for faster rendering by eliminating the need for unnecessary reflows and repaints.

When the browser lays out the page, it needs to be able to flow around replaceable elements such as images. It can begin to render a page even before images are downloaded, provided that it knows the dimensions to wrap non-replaceable elements around. If no dimensions are specified in the containing document, or if the dimensions specified don't match those of the actual images, the browser will require a reflow and repaint once the images are downloaded. To prevent reflows, specify the width and height of all images, either in the HTML <img> tag, or in CSS.

Floppy answered 26/11, 2010 at 18:49 Comment(0)
D
1

The crucial difference between defining width and height in an attribute (as opposed to in CSS) is that it then becomes data, not a presentation parameter. Just imagine managing a following stylesheet

img[src='/images/tree.jpeg'] {
    width: 100px;
    height: 100px;
}

This needlessly entangles CSS with images. It also restricts adaptive layout, i.e. you can no longer have not-yet-loaded images take up correct space when one of their dimensions is inferred (e.g. width: 100%).

Also, consider CSS rules such as object-fit. Confusion about what width and heigth style properties then mean may arise.

Dael answered 8/4, 2017 at 17:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.