img
-
The
img
element embeds an image into the document src
Thesrc
attribute is required, and contains the path to the image you want to embed-
alt
Thealt
attribute holds a textual replacement for the image, which is mandatory and incredibly useful for accessibility usemap
-
The partial
url
, starting with#
, of animage map
associated with the element -
Note that you cannot use this attribute if the
img
element is inside ana
(anchor) element or abutton
element
-
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
srcset
withx-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
-
srcset
defines the set of images that the browser may choose from -
The intrinsic image size in
px
but using thew
unit (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
w
unit (480w
) -
Note the use of the
w
unit, notpx
as you might expect
-
An image filename (
-
elva-fairy-480w.jpg
-
Has dimensions of
480 × 320
-
(⌘
I
on Mac) -
Thus the
srcset
entry for this image is:
srcset="elva-fairy-480w.jpg 480w"
-
Has dimensions of
-
-
sizes
-
sizes
defines 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
hints
to 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"
-