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
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.
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.