Responsive Image Fundamentals
Responsive Image Fundamentals
Article Point
Reference
1. Article Point
For photos and other raster images, the techniques you use might vary a bit, depending on if the images are loaded through CSS or HTML.
There are ways to make background images added to a site through CSS responsive, but unfortunately browser support can be a bit shaky.
We call this use case viewport sizing, and typically this ends up being the most common way that images are made responsive.
For viewport sizing, we typically just need a good ol’ img element with two new attributes:
sizes
andsrcset
.Changes to aspect ratio and cropping are often called
art direction
, and they require a more complicated solution.
To make images responsive, we still need to write CSS rules that will make the image flexible.
img { width: 100%; height: auto; }
The
sizes
andsrcset
attributes are often key to making images responsive.Responsive Image Define:
A method for providing the browser with multiple image sources depending on display density, size of the image element in the page, or any number of other factors.
Srcset Width Descriptors
<img src="cat.jpg" alt="cat" srcset="cat-160.jpg 160w, cat-320.jpg 320w, cat-640.jpg 640w, cat-1280.jpg 1280w">
Sizes
We’re telling the browser what size the image will be in relation to the size of the viewport. And we can tell the browser how that relationship changes as the size of the viewport changes.
<img src="cat.jpg" alt="cat" srcset="cat-160.jpg 160w, cat-320.jpg 320w, cat-640.jpg 640w, cat-1280.jpg 1280w" sizes="(max-width: 480px) 100vw, (max-width: 900px) 33vw, 254px">
Display density descriptors are best for fixed width images
how to solve for art direction.
<picture> <source media="(min-width: 900px)" srcset="cat-vertical.jpg"> <source media="(min-width: 750px)" srcset="cat-horizontal.jpg"> <img src="cat.jpg" alt="cat"> </picture>