r/css • u/coolhotnerd • 28d ago
Question Question on image size attributes for responsive web design
/r/webdevelopment/comments/1xl4bfm/question_on_image_size_attributes_for_responsive/
5
Upvotes
5
u/nextgenfusion 28d 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 28d ago edited 28d 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
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:
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 28d ago
Os atributos
widtheheightno elementoimgsão informações úteis para o navegador saber as dimensões reais do arquivo, sempre use, mesmo que seja um vetor.svgE faz o seu CSS responsivo como tem que ser