Use relative sizes for images
Remember to use relative units when specifying widths for images to prevent them from accidentally overflowing the viewport. For example,
width: 50%;
, will cause the image width to be 50% of the containing element (not the viewport or actual pixel size).
Because CSS allows content to overflow it’s container, it may be necessary use max-width: 100% to prevent images and other content from overflowing. For example:
img, embed, object, video {
max-width: 100%;
}
Be sure to provide meaningful descriptions via the
alt
attribute on
img
elements; these help make your site more accessible by providing context to screen readers and other assistive technologies.
Enhance
img
’s with
srcset
for high DPI devices
The
srcset
attribute enhances the behavior of the
img
element, making it easy to provide multiple image files for different device characteristics. Similar to the
image-set
CSS function
native to CSS,
srcset
allows the browser to choose the best image depending on the characteristics of the device, for example using a 2x image on a 2x display, and potentially in the future, a 1x image on a 2x device when on a limited bandwidth network.
On browsers that don’t support
srcset
, the browser simply uses the default image file specified by the
src
attribute. This is why it is important to always include a 1x image that can be displayed on any device, regardless of capabilities. When
srcset
is supported, the comma-separated list of image/conditions is parsed prior to making any requests, and only the most appropriate image is downloaded and displayed.
While the conditions can include everything from pixel density to width and height, only pixel density is well supported today. To balance current behavior with future features, stick with simply providing the 2x image in the attribute.
Art direction in responsive images with
picture
Changing images based on device characteristics, also known as art direction can be accomplished using the picture element. The
picture
element defines a declarative solution for providing multiple versions of an image based on different characteristics, like device size, device resolution, orientation, and more.