img
-
The
imgelement embeds an image into the document src
Thesrcattribute is required, and contains the path to the image you want to embed-
alt
Thealtattribute holds a textual replacement for the image, which is mandatory and incredibly useful for accessibility usemap-
The partial
url, starting with#, of animage mapassociated with the element -
Note that you cannot use this attribute if the
imgelement is inside ana(anchor) element or abuttonelement
-
The partial
Responsive Images
Resolution Switching (Density Method)
That is, resolution switching with the same size, image but with different resolution-
To achieve this you can allow the browser to choose an appropriate resolution image by
-
using
srcsetwithx-descriptors -
Without the use of
sizes
-
using
-
// HTML <img srcset="elva-fairy-320w.jpg, elva-fairy-480w.jpg 1.5x, elva-fairy-640w.jpg 2x" src="elva-fairy-640w.jpg" alt="Elva dressed as a fairy" /> // CSS img#elva { width: 320px; }
Resolution Switching (srcset/sizes)
That is, display identical image content, but make the image size larger or smaller depending on the deviceThis can be done with two additional
img attributes
-
srcset-
srcsetdefines the set of images that the browser may choose from -
The intrinsic image size in
pxbut using thewunit (see below) - Each set of image information is separated from the previous one by a comma
-
Each contains:
-
An image filename (
elva-fairy-480w.jpg) - A space
-
The image's intrinsic width in pixels using the
wunit (480w) -
Note the use of the
wunit, notpxas you might expect
-
An image filename (
-
elva-fairy-480w.jpg-
Has dimensions of
480 × 320 -
(⌘
Ion Mac) -
Thus the
srcsetentry for this image is:
srcset="elva-fairy-480w.jpg 480w"
-
Has dimensions of
-
-
sizes-
sizesdefines a set of media conditions (e.g. screen widths) and indicates what image size would be best to choose, when certain media conditions are true -
These are
hintsto the browser -
In this case, before each comma we
write
-
A media condition,
(max-width:600px)("when the viewport width is 600 pixels or less") - A space
-
The width of the slot the image will fill when the
media condition is
true (
480px)
-
A media condition,
-
Note: In
sizes, you can use any length value.-
Rather than
providing an absolute width (for example,
480px), you can alternatively provide a width relative to the viewport (for example,50vw) - However, you cannot use a percentage as the slot width
-
Rather than
providing an absolute width (for example,
- The last slot width has no media condition: this is the default that is chosen when none of the media conditions are true.
- The browser ignores everything after the first matching condition: ordering is important.
-
sizes = "(min-width: 850px) 640px, (min-width: 550px) 480px, 320px"
-