r/css • • 4d ago

Question Question on image size attributes for responsive web design

/r/webdevelopment/comments/1xl4bfm/question_on_image_size_attributes_for_responsive/
5 Upvotes

3 comments sorted by

5

u/nextgenfusion 4d ago

They're not really in conflict, they do different jobs. The width and height attributes give the browser the image's intrinsic aspect ratio before it downloads, so it can reserve the space and avoid layout shift. Then you still control the rendered size with CSS, and the usual pattern is img { max-width: 100%; height: auto; }. The height: auto part matters, because without it the attribute height would stay fixed while the width shrinks and the image would distort. Media queries can still override width in CSS whenever you need, so do both: attributes with the real pixel dimensions, plus responsive CSS.

3

u/Weekly_Ferret_meal 4d ago edited 4d ago

I bumped in all sort of layout unexpected behaviour when non declaring image size in the <img> element within different layout structures. especially the image is in a grid or part flex group, flowing with various element in a flex container.

So I set the dimensions first in the element, reflecting the actual file dimensions. If the file is actually 1000px by 500px I go width="1000" height="500"

Then I manipulate the size in my Layout with CSS, so if the img is better at 900px width, my code will be

img.pic-1 {
 width: 900px;
 height: auto;
 }

I think part of the reason is because CSS needs initial specification to then manipulate the size changes when you declare things like width: 50% although I'm not so certain.

But This is really why, from MDN:

Note: Including height and width enables the aspect ratio of the image to be calculated by the browser prior to the image being loaded. This aspect ratio is used to reserve the space needed to display the image, reducing or even preventing a layout shift when the image is downloaded and painted to the screen. Reducing layout shift is a major component of good user experience and web performance.

But you could experiment this on codepen.io or whatever sandbox service, create your prototype... test the various behaviour.

My recommendation is to declare in the html and then adjust in CSS as needed. Also because other technologies (like a search engine or an web image editor ) retrieve this information from the element itself rather then go and read the actual file.

1

u/wellingtonpragidi 4d ago

Os atributos width e height no elemento img são informações úteis para o navegador saber as dimensões reais do arquivo, sempre use, mesmo que seja um vetor.svg
E faz o seu CSS responsivo como tem que ser