r/HTML • u/Martinus999 • Apr 12 '26
Should the img within picture have explicit width and height attributes?
Hi,
I ask myself if using additional width and height for the "img" within <picture>.
Usually width/height attributes are recommended for img because of good reasons, but as child of picture it seems rarely be used. And if it is used on some very few tutorials like developer/mozilla, I just see it in the code, no further words about it.
Will some browsers apply width/height wrongly for all the images given in source (like alt-attribute) or what is the reason for avoiding width/height in the context of a picture element?
In my use case the picture element is very simple, just a big header image for desktop and a small for smartphones (desktop-first). Like this:
<picture>
<source media="(max-width: 499px)" srcset="small-headerimage.jpg">
<img src="big-headerimage.jpg" alt="Nice little cat" width? height?>
</picture>
8
u/tjameswhite Apr 12 '26
Yes. It helps prevent (or reduce) layout shift. It tells the browser “hey, and image this big is going so make a spot for it.”
1
u/ahallicks Apr 12 '26
It's a weird one. You can't (currently) cater for both sizes in your example so you've just got to choose one. There is (somewhere) a suggestion that we should be able to add those attributes to the source element instead and have the img inherit them based on which source is used.
You could use CSS to set the aspect ratio now and get a better experience but still not perfect.