user6777731
user6777731

Reputation:

HTML image width and height attributes in responsive design

It is often said that it's best to specify image sizes in img's HTML attributes, width and height. That way the browser can reserve the space for images that haven't initially been loaded yet, so that once they do load, they don't change the page layout by making the content below them jump as they appear. (I'm sorry to say I don't know what this technique is named so I don't really know how to search for this question specifically, thus this question)

What I'm wondering is how this is solved in responsive layouts? I know on a big desktop browser my news articles' images may be 400x300 px, for example, but I can't put that into my document, as:

<img src="/thumbs/article_image_400_300.jpg" width="400" height="300"/>

Because on a smaller browser I would also like my images to be smaller. But I would still like to keep this behaviour of reserving space, if possible.

Can this be done?

Upvotes: 3

Views: 2464

Answers (1)

jackalope
jackalope

Reputation: 41

Put the height and width attributes into your HTML, showing the actual size of the image file you are using.

Then add this to your CSS to allow images to scale responsively while maintaining their aspect ratio:

img {
  max-width: 100%;
  height: auto;
  width: auto;
}

Now set your desired image width for each breakpoint in your media queries, as a percentage of the width of the parent element.

For example:

img.medium {
  width: 60%;
}

img.small {
  width: 30%;
} 

The widths set in your CSS will override those set in the HTML.

Upvotes: 4

Related Questions