img
elementusemap
attribute: Interactive content.alt
src
srcset
crossorigin
usemap
ismap
width
height
[NamedConstructor=Image(), NamedConstructor=Image(unsigned long width), NamedConstructor=Image(unsigned long width, unsigned long height)] interface HTMLImageElement : HTMLElement { attribute DOMString alt; attribute DOMString src; attribute DOMString srcset; attribute DOMString crossOrigin; attribute DOMString useMap; attribute boolean isMap; attribute unsigned long width; attribute unsigned long height; readonly attribute unsigned long naturalWidth; readonly attribute unsigned long naturalHeight; readonly attribute boolean complete; };
An img
element represents an image.
The image given by the src
and srcset
attributes is the embedded content; the value of the alt
attribute provides
equivalent content for those who cannot process images or who have
image loading disabled (i.e. it is the img
element's fallback
content).
The src
attribute must be
present, and must contain a valid non-empty URL potentially
surrounded by spaces referencing a non-interactive,
optionally animated, image resource that is neither paged nor
scripted.
The srcset
attribute may
also be present. If present, its value must consist of one or more
image candidate strings,
each separated from the next by a U+002C COMMA character (,). This
attribute allows authors to provide alternative images for
environments with smaller screens or screens with higher pixel
densities.
The srcset
attribute allows
authors to provide a set of images to handle graphical displays of
varying dimensions and pixel densities.
The attribute essentially takes a comma-separated list of URLs each with one or more descriptors giving the maximum viewport dimensions and pixel density allowed to use the image. From the available options, the user agent then picks the most appropriate image. If the viewport dimensions or pixel density changes, the user agent can replace the image data with a new image on the fly.
To specify an image, give first a URL, then one or more descriptors of the form 100w, 100h, or 2x, where "100w" means "maximum viewport width of 100 CSS pixels", "100h" is the same but for height, and "2x" means "maximum pixel density of 2 device pixels per CSS pixel".
An image candidate string consists of the following components, in order, with the further restrictions described below this list:
Each image candidate string must have at least one
of the three optional descriptors. There must not be two image candidate strings in a
srcset
attribute whose width
descriptor value, height descriptor value, and pixel
density descriptor value are each identical to their counterpart
in the other image candidate string; for the purposes
of this requirement, omitted width descriptors and height
descriptors are considered to have the value "Infinity", and
omitted pixel density descriptors are considered to have the
value 1.
In this example, a banner that takes half the viewport is provided in two versions, one for wide screen and one for narrow screens.
<h1><img alt="The Breakfast Combo" src="banner.jpeg" srcset="banner-HD.jpeg 2x, banner-phone.jpeg 100w, banner-phone-HD.jpeg 100w 2x"></h1>
Images can thus be static bitmaps (e.g. PNGs, GIFs, JPEGs), single-page vector documents (single-page PDFs, XML files with an SVG root element), animated bitmaps (APNGs, animated GIFs), animated vector graphics (XML files with an SVG root element that use declarative SMIL animation), and so forth. However, this also precludes SVG files with script, multipage PDF files, interactive MNG files, HTML documents, plain text documents, and so forth.
The requirements on the alt
attribute's value are described in the next
section.
The img
element must not be used as a layout tool.
In particular, img
elements should not be used to
display transparent images, as they rarely convey meaning and rarely
add anything useful to the document.
The crossorigin
attribute is a CORS settings attribute. Its purpose is
to allow images from third-party sites that allow cross-origin
access to be used with canvas
.
An img
is always in one of the following states:
When an img
element is either in the partially available state or in the completely available state, it is said to be
available.
An img
element is initially unavailable.
When an img
element is available, it provides a paint
source whose width is the image's intrinsic width, whose
height is the image's intrinsic height, and whose appearance is the
intrinsic appearance of the image.
User agents may obtain images immediately or on demand.
A user agent that obtains images immediately must synchronously
update the image data of an img
element
whenever that element is created with a src
attribute,
a srcset
attribute, or both.
A user agent that obtains images immediately must also synchronously
update the image data of an img
element
whenever that element has its
src
,
srcset
, or
crossorigin
attribute set,
changed, or removed.
A user agent that obtains images on demand must update the
image data of an img
element whenever it needs
the image data (i.e. on demand), but only if the img
element has a
src
or srcset
attribute, and only if the img
element is in the unavailable state. When an img
element's
src
,
srcset
, or
crossorigin
attribute set,
changed, or removed, if the user agent only obtains images on
demand, the img
element must return to the unavailable state.
Each img
element has a last selected
source, which must initially be null, and a current pixel
density, which must initially be undefined.
When an img
element has a current pixel
density that is not 1.0, the element's image data must be
treated as if its resolution, in device pixels per CSS pixels, was
the current pixel density.
For example, if the current pixel density is 3.125, that means that there are 300 device pixels per CSS inch, and thus if the image data is 300x600, it has an intrinsic dimension of 96 CSS pixels by 192 CSS pixels.
Each Document
object must have a list of
available images. Each image in this list is identified by a
tuple consisting of an absolute URL, a CORS
settings attribute mode, and, if the mode is not No CORS, an
origin. User agents may copy entries from one
Document
object's list of available images
to another at any time (e.g. when the Document
is
created, user agents can add to it all the images that are loaded in
other Document
s), but must not change the keys of
entries copied in this way when doing so. User agents may also
remove images from such lists at any time (e.g. to save memory).
When the user agent is to update the image data of an
img
element, it must run the following steps:
Return the img
element to the unavailable state.
If an instance of the fetching algorithm is still running for this element, then abort that algorithm, discarding any pending tasks generated by that algorithm.
Forget the img
element's current image data, if
any.
If the user agent cannot support images, or its support for images has been disabled, then abort these steps.
If the element has a srcset
attribute specified, then
let selected source and selected
pixel density be the URL and pixel density that results from
processing the image candidates, respectively.
Otherwise, if the element has a src
attribute specified and its value
is not the empty string, let selected source
be the value of the element's src
attribute, and selected pixel density be 1.0. Otherwise, let selected source be null and selected
pixel density be undefined.
Let the img
element's last selected
source be selected source and the
img
element's current pixel density be
selected pixel density.
Resolve selected source, relative to the element. If that is not successful, abort these steps.
Let key be a tuple consisting of the
resulting absolute URL, the img
element's
crossorigin
attribute's mode,
and, if that mode is not No
CORS, the Document
object's
origin.
If the list of available images, contains an
entry for key, then set the img
element to the completely available
state, update the presentation of the image appropriately,
queue a task to fire a simple event named
load
at the img
element, and abort these steps.
Asynchronously await a stable state, allowing the task that invoked this algorithm to continue. The synchronous section consists of all the remaining steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)
⌛ If another instance of this algorithm for this
img
element was started after this instance (even if
it aborted and is no longer running), then abort these steps.
Only the last instance takes effect, to avoid
multiple requests when, for example, the
src
,
srcset
, and
crossorigin
attributes
are all set in succession.
⌛ If selected source is null, then
set the element to the broken
state, queue a task to fire a simple
event named error
at the
img
element, and abort these steps.
Do a potentially CORS-enabled fetch of the
absolute URL that resulted from the earlier step,
with the mode being the state of the element's crossorigin
content attribute,
the origin being the origin of the
img
element's Document
, and the
default origin behaviour set to taint.
The resource obtained in this fashion, if any, is the
img
element's image data. It can be either
CORS-same-origin or CORS-cross-origin;
this affects the origin of the image itself (e.g.
when used on a canvas
).
Fetching the image must delay the load event of the element's document until the task that is queued by the networking task source once the resource has been fetched (defined below) has been run.
This, unfortunately, can be used to perform a rudimentary port scan of the user's local network (especially in conjunction with scripting, though scripting isn't actually necessary to carry out such an attack). User agents may implement cross-origin access control policies that are stricter than those described above to mitigate this attack, but unfortunately such policies are typically not compatible with existing Web content.
The first task that is queued by the networking task
source while the image is being fetched must set the img
element's
state to partially available.
If the resource is in a supported image format, then each task that is queued by the networking task source while the image is being fetched must update the presentation of the image appropriately (e.g. if the image is a progressive JPEG, each packet can improve the resolution of the image); furthermore, the last task that is queued by the networking task source once the resource has been fetched must act as appropriate given the following alternatives:
img
element to the completely available state, update the
presentation of the image appropriately, add the image to the
list of available images using the key key, and fire a simple event named
load
at the img
element.img
element to the broken state, and fire a simple
event named error
at the
img
element.On the other hand, if the resource type is
multipart/x-mixed-replace
, then each task that is queued by the networking task source
while the image is being fetched must
also update the presentation of the image, but as each new body
part comes in, it must replace the previous image. Once one body
part has been completely decoded, the user agent must set the
img
element to the completely
available state and queue a task to fire
a simple event named load
at the img
element.
If at any point the user agent discovers that the image data is
corrupted in some fatal way, or that the image data is not in a
supported file format, then the user agent must set the
img
element to the broken state. If the fetching algorithm is still running for this
element, then the user agent must also abort that algorithm,
discarding any pending tasks
generated by that algorithm, and then queue a task to
fire a simple event named error
at the img
element.
While a user agent is running the above algorithm for an element
x, there must be a strong reference from the
element's Document
to the element x, even if that element is not in its Document
.
When an img
element is in the completely available state and the
user agent can decode the media data without errors, then the
img
element is said to be fully
decodable.
Whether the image is fetched successfully or not (e.g. whether the response code was a 2xx code or equivalent) must be ignored when determining the image's type and whether it is a valid image.
This allows servers to return images with error responses, and have them displayed.
The user agents should apply the image sniffing rules to determine the type of the image, with the image's associated Content-Type headers giving the official type. If these rules are not applied, then the type of the image must be the type given by the image's associated Content-Type headers.
User agents must not support non-image resources with the
img
element (e.g. XML files whose root element is an
HTML element). User agents must not run executable code
(e.g. scripts) embedded in the image resource. User agents must only
display the first page of a multipage resource (e.g. a PDF
file). User agents must not allow the resource to act in an
interactive fashion, but should honor any animation in the
resource.
This specification does not specify which image types are to be supported.
When the user agent is required to process the image candidates of an
img
element's srcset
attribute, the user agent must
run the following steps, which return a URL and pixel density (null
and undefined respectively if no selection can be made):
Let input be the value of the
img
element's srcset
attribute.
Let position be a pointer into input, initially pointing at the start of the string.
Let raw candidates be an initially empty ordered list of URLs with associated unparsed descriptors. The order of entries in the list is the order in which entries are added to the list.
Splitting loop: Skip whitespace.
Collect a sequence of characters that are not space characters, and let that be url.
If url is empty, then jump to the step labeled descriptor parser.
Collect a sequence of characters that are not U+002C COMMA characters (,), and let that be descriptors.
Add url to raw candidates, associated with descriptors.
If position is past the end of input, then jump to the step labeled descriptor parser.
Advance position to the next character in input (skipping past the U+002C COMMA character (,) separating this candidate from the next).
Return to the step labeled splitting loop.
Descriptor parser: Let candidates be an initially empty ordered list of URLs each with an associated pixel density, and optionally an associated width and/or height. The order of entries in the list is the order in which entries are added to the list.
For each entry in raw candidates with URL url associated with the unparsed descriptors unparsed descriptors, in the order they were originally added to the list, run these substeps:
Let descriptor list be the result of splitting unparsed descriptors on spaces.
Let error be no.
Let width be absent.
Let height be absent.
Let density be absent.
For each token in descriptor list, run the appropriate set of steps from the following list:
If width is not absent, then let error be yes.
Apply the rules for parsing non-negative integers to the token. Let width be the result.
If height is not absent, then let error be yes.
Apply the rules for parsing non-negative integers to the token. Let height be the result.
If density is not absent, then let error be yes.
Apply the rules for parsing floating-point number values to the token. Let density be the result.
If width is still absent, set it to Infinity.
If height is still absent, set it to Infinity.
If density is still absent, set it to 1.0.
If error is still no, then add an entry to candidates whose URL is url, associated with a width width, a height height, and a pixel density density.
If the img
element has a src
attribute whose value is not the
empty string, then run the following substeps:
If candidates is empty, return null and undefined and abort these steps.
If an entry b in candidates has the same associated width, height, and pixel density as an earlier entry a in candidates, then remove entry b. Repeat this step until none of the entries in candidates have the same associated width, height, and pixel density as an earlier entry.
Optionally, return the URL of an entry in candidates chosen by the user agent, and that entry's associated pixel density, and then abort these steps. The user agent may apply any algorithm or heuristic in its selection of an entry for the purposes of this step.
This allows a user agent to override the default algorithm (as described in subsequent steps) in case the user agent has a reason to do so. For example, it would allow the user agent in highly bandwidth-constrained conditions to intentionally opt to use an image intended for a smaller screen size, on the assumption that it'll probably be good enough. Implementors are urged to avoid doing this if at all possible, to let authors have predictable results. The results of using an image intended for a different viewport size can be, at a minimum, aesthetically displeasing.
This clause is not necessary to select images that are of lower pixel density than the display can handle, because the definition of pixel density below is also left up to the user agent. This step is only needed to allow user agents to pick images intended for viewports with other dimensions.
Let max width be the width of the viewport, and let max height be the height of the viewport. [CSS]
If there are any entries in candidates that have an associated width that is less than max width, then remove them, unless that would remove all the entries, in which case remove only the entries whose associated width is less than the greatest such width.
If there are any entries in candidates that have an associated height that is less than max height, then remove them, unless that would remove all the entries, in which case remove only the entries whose associated height is less than the greatest such height.
If there are any entries in candidates that have an associated pixel density that is less than a user-agent-defined value giving the nominal pixel density of the display, then remove them, unless that would remove all the entries, in which case remove only the entries whose associated pixel density is less than the greatest such pixel density.
Remove all the entries in candidates that have an associated width that is greater than the smallest such width.
Remove all the entries in candidates that have an associated height that is greater than the smallest such height.
Remove all the entries in candidates that have an associated pixel density that is greater than the smallest such pixel density.
Return the URL of the sole remaining entry in candidates, and that entry's associated pixel density.
The user agent may at any time run the following algorithm to
update an img
element's image in order to react to
changes in the environment. (User agents are not required
to ever run this algorithm.)
Asynchronously await a stable state. The synchronous section consists of all the remaining steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)
⌛ If the img
element does not have a
srcset
attribute specified, is
not in the completely available state,
has image data whose resource type is
multipart/x-mixed-replace
, or if its update the
image data algorithm is running, then abort this
algorithm.
⌛ Let selected source and selected pixel density be the URL and pixel density that results from processing the image candidates, respectively.
⌛ If selected source is null, then abort these steps.
⌛ If selected source and selected pixel density are the same as the element's last selected source and current pixel density, then abort these steps.
⌛ Resolve selected source, relative to the element.
⌛ Let CORS mode be the state of
the element's crossorigin
content attribute.
⌛ If the resolve a URL algorithm is not successful, abort these steps.
End the synchronous section, continuing the remaining steps asynchronously.
Do a potentially CORS-enabled fetch of the
resulting absolute URL, with the mode being
CORS mode, the origin being
the origin of the img
element's
Document
, and the default origin behaviour set
to taint.
If this download fails in any way (other than the response code
not being a 2xx code, as mentioned earlier), or if the image
format is unsupported (as determined by applying the image sniffing rules,
again as mentioned earlier), or if the resource type is
multipart/x-mixed-replace
, then abort these
steps.
Otherwise, wait for the fetch algorithm to queue its last task, and then continue with these steps. The data obtained in this way is used in the steps below.
Queue a task to run the following substeps:
If the img
element's src
, srcset
, or crossorigin
attributes have
been set, changed, or removed since this algorithm started, then
abort these steps.
Let the img
element's last selected
source be selected source and the
img
element's current pixel density be
selected pixel density.
Replace the img
element's image data with the
resource obtained by the earlier step of this algorithm. It can
be either CORS-same-origin or
CORS-cross-origin; this affects the
origin of the image itself (e.g. when used on a
canvas
).
Fire a simple event named load
at the img
element.
The task source for the tasks queued by algorithms in this section is the DOM manipulation task source.
What an img
element represents depends on the src
attribute and the alt
attribute.
src
attribute is set
and the alt
attribute is set to
the empty stringThe image is either decorative or supplemental to the rest of the content, redundant with some other information in the document.
If the image is available and the user agent is configured to display that image, then the element represents the element's image data.
Otherwise, the element represents nothing, and may be omitted completely from the rendering. User agents may provide the user with a notification that an image is present but has been omitted from the rendering.
src
attribute is set
and the alt
attribute is set to a
value that isn't emptyThe image is a key part of the content; the alt
attribute gives a textual
equivalent or replacement for the image.
If the image is available and the user agent is configured to display that image, then the element represents the element's image data.
Otherwise, the element represents the text given
by the alt
attribute. User
agents may provide the user with a notification that an image is
present but has been omitted from the rendering.
src
attribute is set
and the alt
attribute is notThe image might be a key part of the content, and there is no textual equivalent of the image available.
In a conforming document, the absence of the alt
attribute indicates that the image
is a key part of the content but that a textual replacement for
the image was not available when the image was generated.
If the image is available and the user agent is configured to display that image, then the element represents the element's image data.
Otherwise, the user agent should display some sort of indicator that there is an image that is not being rendered, and may, if requested by the user, or if so configured, or when required to provide contextual information in response to navigation, provide caption information for the image, derived as follows:
If the image has a title
attribute whose value is not the empty string, then the value of
that attribute is the caption information; abort these
steps.
If the image is a descendant of a figure
element that has a child figcaption
element, and,
ignoring the figcaption
element and its descendants,
the figure
element has no Text
node
descendants other than inter-element whitespace, and
no embedded content descendant other than the
img
element, then the contents of the first such
figcaption
element are the caption information;
abort these steps.
src
attribute is not
set and either the alt
attribute
is set to the empty string or the alt
attribute is not set at allThe element represents nothing.
The element represents the text given by the alt
attribute.
The alt
attribute does not
represent advisory information. User agents must not present the
contents of the alt
attribute in
the same way as content of the title
attribute.
User agents may always provide the user with the option to display any image, or to prevent any image from being displayed. User agents may also apply heuristics to help the user make use of the image when the user is unable to see it, e.g. due to a visual disability or because they are using a text terminal with no graphics capabilities. Such heuristics could include, for instance, optical character recognition (OCR) of text found within the image.
While user agents are encouraged to repair cases
of missing alt
attributes, authors
must not rely on such behavior. Requirements for
providing text to act as an alternative for images are described
in detail below.
The contents of img
elements, if any, are
ignored for the purposes of rendering.
The usemap
attribute,
if present, can indicate that the image has an associated
image map.
The ismap
attribute, when used on an element that is a descendant of an
a
element with an href
attribute, indicates by its
presence that the element provides access to a server-side image
map. This affects how events are handled on the corresponding
a
element.
The ismap
attribute is a
boolean attribute. The attribute must not be specified
on an element that does not have an ancestor a
element
with an href
attribute.
The img
element supports dimension
attributes.
The alt
, src
,
and srcset
IDL attributes must reflect the respective content
attributes of the same name.
The crossOrigin
IDL
attribute must reflect the crossorigin
content
attribute.
The useMap
IDL
attribute must reflect the usemap
content attribute.
The isMap
IDL
attribute must reflect the ismap
content attribute.
width
[ = value ]height
[ = value ]These attributes return the actual rendered dimensions of the image, or zero if the dimensions are not known.
They can be set, to change the corresponding content attributes.
naturalWidth
naturalHeight
These attributes return the intrinsic dimensions of the image, or zero if the dimensions are not known.
complete
Returns true if the image has been completely downloaded or if no image is specified; otherwise, returns false.
Image
( [ width [, height ] ] )Returns a new img
element, with the width
and height
attributes set to the values
passed in the relevant arguments, if applicable.
The IDL attributes width
and height
must return the
rendered width and height of the image, in CSS pixels, if the image
is being rendered, and is being rendered to a visual
medium; or else the intrinsic width and height of the image, in CSS
pixels, if the image is available but
not being rendered to a visual medium; or else 0, if the image is
not available. [CSS]
On setting, they must act as if they reflected the respective content attributes of the same name.
The IDL attributes naturalWidth
and
naturalHeight
must return the intrinsic width and height of the image, in CSS
pixels, if the image is available, or
else 0. [CSS]
The IDL attribute complete
must return
true if any of the following conditions is true:
src
attribute is omitted.
src
attribute's value is the empty string.
img
element is not in the broken state.
img
element is completely available.
Otherwise, the attribute must return false.
The value of complete
can thus change while a
script is executing.
Three constructors are provided for creating
HTMLImageElement
objects (in addition to the factory
methods from DOM Core such as createElement()
): Image()
, Image(width)
, and Image(width, height)
. When invoked as constructors,
these must return a new HTMLImageElement
object (a new
img
element). If the width argument
is present, the new object's width
content attribute must be set to
width. If the height
argument is also present, the new object's height
content attribute must be set
to height. The element's document must be the
active document of the browsing context of
the Window
object on which the interface object of the
invoked constructor is found.
A single image can have different appropriate alternative text depending on the context.
In each of the following cases, the same image is used, yet the
alt
text is different each
time. The image is the coat of arms of the Carouge municipality in
the canton Geneva in Switzerland.
Here it is used as a supplementary icon:
<p>I lived in <img src="carouge.svg" alt=""> Carouge.</p>
Here it is used as an icon representing the town:
<p>Home town: <img src="carouge.svg" alt="Carouge"></p>
Here it is used as part of a text on the town:
<p>Carouge has a coat of arms.</p> <p><img src="carouge.svg" alt="The coat of arms depicts a lion, sitting in front of a tree."></p> <p>It is used as decoration all over the town.</p>
Here it is used as a way to support a similar text where the description is given as well as, instead of as an alternative to, the image:
<p>Carouge has a coat of arms.</p> <p><img src="carouge.svg" alt=""></p> <p>The coat of arms depicts a lion, sitting in front of a tree. It is used as decoration all over the town.</p>
Here it is used as part of a story:
<p>He picked up the folder and a piece of paper fell out.</p> <p><img src="carouge.svg" alt="Shaped like a shield, the paper had a red background, a green tree, and a yellow lion with its tongue hanging out and whose tail was shaped like an S."></p> <p>He stared at the folder. S! The answer he had been looking for all this time was simply the letter S! How had he not seen that before? It all came together now. The phone call where Hector had referred to a lion's tail, the time Marco had stuck his tongue out...</p>
Here it is not known at the time of publication what the image
will be, only that it will be a coat of arms of some kind, and thus
no replacement text can be provided, and instead only a brief
caption for the image is provided, in the title
attribute:
<p>The last user to have uploaded a coat of arms uploaded this one:</p> <p><img src="last-uploaded-coat-of-arms.cgi" title="User-uploaded coat of arms."></p>
Ideally, the author would find a way to provide real replacement text even in this case, e.g. by asking the previous user. Not providing replacement text makes the document more difficult to use for people who are unable to view images, e.g. blind users, or users or very low-bandwidth connections or who pay by the byte, or users who are forced to use a text-only Web browser.
Here are some more examples showing the same picture used in different contexts, with different appropriate alternate texts each time.
<article> <h1>My cats</h1> <h2>Fluffy</h2> <p>Fluffy is my favorite.</p> <img src="fluffy.jpg" alt="She likes playing with a ball of yarn."> <p>She's just too cute.</p> <h2>Miles</h2> <p>My other cat, Miles just eats and sleeps.</p> </article>
<article> <h1>Photography</h1> <h2>Shooting moving targets indoors</h2> <p>The trick here is to know how to anticipate; to know at what speed and what distance the subject will pass by.</p> <img src="fluffy.jpg" alt="A cat flying by, chasing a ball of yarn, can be photographed quite nicely using this technique."> <h2>Nature by night</h2> <p>To achieve this, you'll need either an extremely sensitive film, or immense flash lights.</p> </article>
<article> <h1>About me</h1> <h2>My pets</h2> <p>I've got a cat named Fluffy and a dog named Miles.</p> <img src="fluffy.jpg" alt="Fluffy, my cat, tends to keep itself busy."> <p>My dog Miles and I like go on long walks together.</p> <h2>music</h2> <p>After our walks, having emptied my mind, I like listening to Bach.</p> </article>
<article> <h1>Fluffy and the Yarn</h1> <p>Fluffy was a cat who liked to play with yarn. He also liked to jump.</p> <aside><img src="fluffy.jpg" alt="" title="Fluffy"></aside> <p>He would play in the morning, he would play in the evening.</p> </article>
Except where otherwise specified, the alt
attribute must be specified and its
value must not be empty; the value must be an appropriate
replacement for the image. The specific requirements for the alt
attribute depend on what the image
is intended to represent, as described in the following
sections.
The most general rule to consider when writing alternative text
is the following: the intent is that replacing every image
with the text of its alt
attribute
not change the meaning of the page.
So, in general, alternative text can be written by considering what one would have written had one not been able to include the image.
A corollary to this is that the alt
attribute's value should never
contain text that could be considered the image's caption,
title, or legend. It is supposed to contain
replacement text that could be used by users instead of the
image; it is not meant to supplement the image. The title
attribute can be used for
supplemental information.
Another corollary is that the alt
attribute's value should not repeat
information that is already provided in the prose next to the
image.
One way to think of alternative text is to think about how you would read the page containing the image to someone over the phone, without mentioning that there is an image present. Whatever you say instead of the image is typically a good start for writing the alternative text.
When an a element that creates a
hyperlink, or a button
element, has no
textual content but contains one or more images, the alt
attributes must contain text that
together convey the purpose of the link or button.
In this example, a user is asked to pick his preferred color from a list of three. Each color is given by an image, but for users who have configured their user agent not to display images, the color names are used instead:
<h1>Pick your color</h1> <ul> <li><a href="green.html"><img src="green.jpeg" alt="Green"></a></li> <li><a href="blue.html"><img src="blue.jpeg" alt="Blue"></a></li> <li><a href="red.html"><img src="red.jpeg" alt="Red"></a></li> </ul>
In this example, each button has a set of images to indicate the kind of color output desired by the user. The first image is used in each case to give the alternative text.
<button name="rgb"><img src="red" alt="RGB"><img src="green" alt=""><img src="blue" alt=""></button> <button name="cmyk"><img src="cyan" alt="CMYK"><img src="magenta" alt=""><img src="yellow" alt=""><img src="black" alt=""></button>
Since each image represents one part of the text, it could also be written like this:
<button name="rgb"><img src="red" alt="R"><img src="green" alt="G"><img src="blue" alt="B"></button> <button name="cmyk"><img src="cyan" alt="C"><img src="magenta" alt="M"><img src="yellow" alt="Y"><img src="black" alt="K"></button>
However, with other alternative text, this might not work, and putting all the alternative text into one image in each case might make more sense:
<button name="rgb"><img src="red" alt="sRGB profile"><img src="green" alt=""><img src="blue" alt=""></button> <button name="cmyk"><img src="cyan" alt="CMYK profile"><img src="magenta" alt=""><img src="yellow" alt=""><img src="black" alt=""></button>
Sometimes something can be more clearly stated in graphical
form, for example as a flowchart, a diagram, a graph, or a simple
map showing directions. In such cases, an image can be given using
the img
element, but the lesser textual version must
still be given, so that users who are unable to view the image
(e.g. because they have a very slow connection, or because they
are using a text-only browser, or because they are listening to
the page being read out by a hands-free automobile voice Web
browser, or simply because they are blind) are still able to
understand the message being conveyed.
The text must be given in the alt
attribute, and must convey the
same message as the image specified in the src
attribute.
It is important to realize that the alternative text is a replacement for the image, not a description of the image.
In the following example we have a flowchart in image
form, with text in the alt
attribute rephrasing the flowchart in prose form:
<p>In the common case, the data handled by the tokenization stage comes from the network, but it can also come from script.</p> <p><img src="images/parsing-model-overview.png" alt="The Network passes data to the Input Stream Preprocessor, which passes it to the Tokenizer, which passes it to the Tree Construction stage. From there, data goes to both the DOM and to Script Execution. Script Execution is linked to the DOM, and, using document.write(), passes data to the Tokenizer."></p>
Here's another example, showing a good solution and a bad solution to the problem of including an image in a description.
First, here's the good solution. This sample shows how the alternative text should just be what you would have put in the prose if the image had never existed.
<!-- This is the correct way to do things. --> <p> You are standing in an open field west of a house. <img src="house.jpeg" alt="The house is white, with a boarded front door."> There is a small mailbox here. </p>
Second, here's the bad solution. In this incorrect way of doing things, the alternative text is simply a description of the image, instead of a textual replacement for the image. It's bad because when the image isn't shown, the text doesn't flow as well as in the first example.
<!-- This is the wrong way to do things. --> <p> You are standing in an open field west of a house. <img src="house.jpeg" alt="A white house, with a boarded front door."> There is a small mailbox here. </p>
Text such as "Photo of white house with boarded door" would be
equally bad alternative text (though it could be suitable for the
title
attribute or in the
figcaption
element of a figure
with this
image).
A document can contain information in iconic form. The icon is intended to help users of visual browsers to recognize features at a glance.
In some cases, the icon is supplemental to a text label
conveying the same meaning. In those cases, the alt
attribute must be present but must
be empty.
Here the icons are next to text that conveys the same meaning,
so they have an empty alt
attribute:
<nav> <p><a href="/help/"><img src="/icons/help.png" alt=""> Help</a></p> <p><a href="/configure/"><img src="/icons/configuration.png" alt=""> Configuration Tools</a></p> </nav>
In other cases, the icon has no text next to it describing what
it means; the icon is supposed to be self-explanatory. In those
cases, an equivalent textual label must be given in the alt
attribute.
Here, posts on a news site are labeled with an icon indicating their topic.
<body> <article> <header> <h1>Ratatouille wins <i>Best Movie of the Year</i> award</h1> <p><img src="movies.png" alt="Movies"></p> </header> <p>Pixar has won yet another <i>Best Movie of the Year</i> award, making this its 8th win in the last 12 years.</p> </article> <article> <header> <h1>Latest TWiT episode is online</h1> <p><img src="podcasts.png" alt="Podcasts"></p> </header> <p>The latest TWiT episode has been posted, in which we hear several tech news stories as well as learning much more about the iPhone. This week, the panelists compare how reflective their iPhones' Apple logos are.</p> </article> </body>
Many pages include logos, insignia, flags, or emblems, which stand for a particular entity such as a company, organization, project, band, software package, country, or some such.
If the logo is being used to represent the entity, e.g. as a page
heading, the alt
attribute must
contain the name of the entity being represented by the logo. The
alt
attribute must not
contain text like the word "logo", as it is not the fact that it is
a logo that is being conveyed, it's the entity itself.
If the logo is being used next to the name of the entity that
it represents, then the logo is supplemental, and its alt
attribute must instead be
empty.
If the logo is merely used as decorative material (as branding, or, for example, as a side image in an article that mentions the entity to which the logo belongs), then the entry below on purely decorative images applies. If the logo is actually being discussed, then it is being used as a phrase or paragraph (the description of the logo) with an alternative graphical representation (the logo itself), and the first entry above applies.
In the following snippets, all four of the above cases are present. First, we see a logo used to represent a company:
<h1><img src="XYZ.gif" alt="The XYZ company"></h1>
Next, we see a paragraph which uses a logo right next to the company name, and so doesn't have any alternative text:
<article> <h2>News</h2> <p>We have recently been looking at buying the <img src="alpha.gif" alt=""> ΑΒΓ company, a small Greek company specializing in our type of product.</p>
In this third snippet, we have a logo being used in an aside, as part of the larger article discussing the acquisition:
<aside><p><img src="alpha-large.gif" alt=""></p></aside> <p>The ΑΒΓ company has had a good quarter, and our pie chart studies of their accounts suggest a much bigger blue slice than its green and orange slices, which is always a good sign.</p> </article>
Finally, we have an opinion piece talking about a logo, and the logo is therefore described in detail in the alternative text.
<p>Consider for a moment their logo:</p> <p><img src="/images/logo" alt="It consists of a green circle with a green question mark centered inside it."></p> <p>How unoriginal can you get? I mean, oooooh, a question mark, how <em>revolutionary</em>, how utterly <em>ground-breaking</em>, I'm sure everyone will rush to adopt those specifications now! They could at least have tried for some sort of, I don't know, sequence of rounded squares with varying shades of green and bold white outlines, at least that would look good on the cover of a blue book.</p>
This example shows how the alternative text should be written such that if the image isn't available, and the text is used instead, the text flows seamlessly into the surrounding text, as if the image had never been there in the first place.
Sometimes, an image just consists of text, and the purpose of the image is not to highlight the actual typographic effects used to render the text, but just to convey the text itself.
In such cases, the alt
attribute must be present but must consist of the same text as
written in the image itself.
Consider a graphic containing the text "Earth Day", but with the letters all decorated with flowers and plants. If the text is merely being used as a heading, to spice up the page for graphical users, then the correct alternative text is just the same text "Earth Day", and no mention need be made of the decorations:
<h1><img src="earthdayheading.png" alt="Earth Day"></h1>
In many cases, the image is actually just supplementary, and
its presence merely reinforces the surrounding text. In these
cases, the alt
attribute must be
present but its value must be the empty string.
In general, an image falls into this category if removing the image doesn't make the page any less useful, but including the image makes it a lot easier for users of visual browsers to understand the concept.
A flowchart that repeats the previous paragraph in graphical form:
<p>The Network passes data to the Input Stream Preprocessor, which passes it to the Tokenizer, which passes it to the Tree Construction stage. From there, data goes to both the DOM and to Script Execution. Script Execution is linked to the DOM, and, using document.write(), passes data to the Tokenizer.</p> <p><img src="images/parsing-model-overview.png" alt=""></p>
In these cases, it would be wrong to include alternative text
that consists of just a caption. If a caption is to be included,
then either the title
attribute can
be used, or the figure
and figcaption
elements can be used. In the latter case, the image would in fact
be a phrase or paragraph with an alternative graphical
representation, and would thus require alternative text.
<!-- Using the title="" attribute --> <p>The Network passes data to the Input Stream Preprocessor, which passes it to the Tokenizer, which passes it to the Tree Construction stage. From there, data goes to both the DOM and to Script Execution. Script Execution is linked to the DOM, and, using document.write(), passes data to the Tokenizer.</p> <p><img src="images/parsing-model-overview.png" alt="" title="Flowchart representation of the parsing model."></p>
<!-- Using <figure> and <figcaption> --> <p>The Network passes data to the Input Stream Preprocessor, which passes it to the Tokenizer, which passes it to the Tree Construction stage. From there, data goes to both the DOM and to Script Execution. Script Execution is linked to the DOM, and, using document.write(), passes data to the Tokenizer.</p> <figure> <img src="images/parsing-model-overview.png" alt="The Network leads to the Input Stream Preprocessor, which leads to the Tokenizer, which leads to the Tree Construction stage. The Tree Construction stage leads to two items. The first is Script Execution, which leads via document.write() back to the Tokenizer. The second item from which Tree Construction leads is the DOM. The DOM is related to the Script Execution."> <figcaption>Flowchart representation of the parsing model.</figcaption> </figure>
<!-- This is WRONG. Do not do this. Instead, do what the above examples do. --> <p>The Network passes data to the Input Stream Preprocessor, which passes it to the Tokenizer, which passes it to the Tree Construction stage. From there, data goes to both the DOM and to Script Execution. Script Execution is linked to the DOM, and, using document.write(), passes data to the Tokenizer.</p> <p><img src="images/parsing-model-overview.png" alt="Flowchart representation of the parsing model."></p> <!-- Never put the image's caption in the alt="" attribute! -->
A graph that repeats the previous paragraph in graphical form:
<p>According to a study covering several billion pages, about 62% of documents on the Web in 2007 triggered the Quirks rendering mode of Web browsers, about 30% triggered the Almost Standards mode, and about 9% triggered the Standards mode.</p> <p><img src="rendering-mode-pie-chart.png" alt=""></p>
If an image is decorative but isn't especially page-specific — for example an image that forms part of a site-wide design scheme — the image should be specified in the site's CSS, not in the markup of the document.
However, a decorative image that isn't discussed by the
surrounding text but still has some relevance can be included in a page
using the img
element. Such images are decorative, but
still form part of the content. In these cases, the alt
attribute must be present but its
value must be the empty string.
Examples where the image is purely decorative despite being relevant would include things like a photo of the Black Rock City landscape in a blog post about an event at Burning Man, or an image of a painting inspired by a poem, on a page reciting that poem. The following snippet shows an example of the latter case (only the first verse is included in this snippet):
<h1>The Lady of Shalott</h1> <p><img src="shalott.jpeg" alt=""></p> <p>On either side the river lie<br> Long fields of barley and of rye,<br> That clothe the wold and meet the sky;<br> And through the field the road run by<br> To many-tower'd Camelot;<br> And up and down the people go,<br> Gazing where the lilies blow<br> Round an island there below,<br> The island of Shalott.</p>
When a picture has been sliced into smaller image files that are
then displayed together to form the complete picture again, one of
the images must have its alt
attribute set as per the relevant rules that would be appropriate
for the picture as a whole, and then all the remaining images must
have their alt
attribute set to
the empty string.
In the following example, a picture representing a company logo for XYZ Corp has been split into two pieces, the first containing the letters "XYZ" and the second with the word "Corp". The alternative text ("XYZ Corp") is all in the first image.
<h1><img src="logo1.png" alt="XYZ Corp"><img src="logo2.png" alt=""></h1>
In the following example, a rating is shown as three filled stars and two empty stars. While the alternative text could have been "★★★☆☆", the author has instead decided to more helpfully give the rating in the form "3 out of 5". That is the alternative text of the first image, and the rest have blank alternative text.
<p>Rating: <meter max=5 value=3><img src="1" alt="3 out of 5" ><img src="1" alt=""><img src="1" alt=""><img src="0" alt="" ><img src="0" alt=""></meter></p>
Generally, image maps should be used instead of slicing an image for links.
However, if an image is indeed sliced and any of the components
of the sliced picture are the sole contents of links, then one image
per link must have alternative text in its alt
attribute representing the purpose
of the link.
In the following example, a picture representing the flying spaghetti monster emblem, with each of the left noodly appendages and the right noodly appendages in different images, so that the user can pick the left side or the right side in an adventure.
<h1>The Church</h1> <p>You come across a flying spaghetti monster. Which side of His Noodliness do you wish to reach out for?</p> <p><a href="?go=left" ><img src="fsm-left.png" alt="Left side. "></a ><img src="fsm-middle.png" alt="" ><a href="?go=right"><img src="fsm-right.png" alt="Right side."></a></p>
In some cases, the image is a critical part of the content. This could be the case, for instance, on a page that is part of a photo gallery. The image is the whole point of the page containing it.
How to provide alternative text for an image that is a key part of the content depends on the image's provenance.
When it is possible for detailed alternative text to be
provided, for example if the image is part of a series of
screenshots in a magazine review, or part of a comic strip, or is
a photograph in a blog entry about that photograph, text that can
serve as a substitute for the image must be given as the contents
of the alt
attribute.
A screenshot in a gallery of screenshots for a new OS, with some alternative text:
<figure> <img src="KDE%20Light%20desktop.png" alt="The desktop is blue, with icons along the left hand side in two columns, reading System, Home, K-Mail, etc. A window is open showing that menus wrap to a second line if they cannot fit in the window. The window has a list of icons along the top, with an address bar below it, a list of icons for tabs along the left edge, a status bar on the bottom, and two panes in the middle. The desktop has a bar at the bottom of the screen with a few buttons, a pager, a list of open applications, and a clock."> <figcaption>Screenshot of a KDE desktop.</figcaption> </figure>
A graph in a financial report:
<img src="sales.gif" title="Sales graph" alt="From 1998 to 2005, sales increased by the following percentages with each year: 624%, 75%, 138%, 40%, 35%, 9%, 21%">
Note that "sales graph" would be inadequate alternative text for a sales graph. Text that would be a good caption is not generally suitable as replacement text.
In certain cases, the nature of the image might be such that providing thorough alternative text is impractical. For example, the image could be indistinct, or could be a complex fractal, or could be a detailed topographical map.
In these cases, the alt
attribute must contain some suitable alternative text, but it may
be somewhat brief.
Sometimes there simply is no text that can do justice to an image. For example, there is little that can be said to usefully describe a Rorschach inkblot test. However, a description, even if brief, is still better than nothing:
<figure> <img src="/commons/a/a7/Rorschach1.jpg" alt="A shape with left-right symmetry with indistinct edges, with a small gap in the center, two larger gaps offset slightly from the center, with two similar gaps under them. The outline is wider in the top half than the bottom half, with the sides extending upwards higher than the center, and the center extending below the sides."> <figcaption>A black outline of the first of the ten cards in the Rorschach inkblot test.</figcaption> </figure>
Note that the following would be a very bad use of alternative text:
<!-- This example is wrong. Do not copy it. --> <figure> <img src="/commons/a/a7/Rorschach1.jpg" alt="A black outline of the first of the ten cards in the Rorschach inkblot test."> <figcaption>A black outline of the first of the ten cards in the Rorschach inkblot test.</figcaption> </figure>
Including the caption in the alternative text like this isn't useful because it effectively duplicates the caption for users who don't have images, taunting them twice yet not helping them any more than if they had only read or heard the caption once.
Another example of an image that defies full description is a fractal, which, by definition, is infinite in detail.
The following example shows one possible way of providing alternative text for the full view of an image of the Mandelbrot set.
<img src="ms1.jpeg" alt="The Mandelbrot set appears as a cardioid with its cusp on the real axis in the positive direction, with a smaller bulb aligned along the same center line, touching it in the negative direction, and with these two shapes being surrounded by smaller bulbs of various sizes.">
In some unfortunate cases, there might be no alternative text available at all, either because the image is obtained in some automated fashion without any associated alternative text (e.g. a Webcam), or because the page is being generated by a script using user-provided images where the user did not provide suitable or usable alternative text (e.g. photograph sharing sites), or because the author does not himself know what the images represent (e.g. a blind photographer sharing an image on his blog).
In such cases, the alt
attribute may be omitted, but one of the following conditions must
be met as well:
title
attribute is
present and has a non-empty value.img
element
is in a figure
element that contains a
figcaption
element that contains content other than
inter-element whitespace, and, ignoring the
figcaption
element and its descendants, the
figure
element has no Text
node
descendants other than inter-element whitespace, and
no embedded content descendant other than the
img
element.Such cases are to be kept to an absolute
minimum. If there is even the slightest possibility of the author
having the ability to provide real alternative text, then it would
not be acceptable to omit the alt
attribute.
A photo on a photo-sharing site, if the site received the image with no metadata other than the caption, could be marked up as follows:
<figure> <img src="1100670787_6a7c664aef.jpg"> <figcaption>Bubbles traveled everywhere with us.</figcaption> </figure>
It would be better, however, if a detailed description of the important parts of the image obtained from the user and included on the page.
A blind user's blog in which a photo taken by the user is shown. Initially, the user might not have any idea what the photo he took shows:
<article> <h1>I took a photo</h1> <p>I went out today and took a photo!</p> <figure> <img src="photo2.jpeg"> <figcaption>A photograph taken blindly from my front porch.</figcaption> </figure> </article>
Eventually though, the user might obtain a description of the image from his friends and could then include alternative text:
<article> <h1>I took a photo</h1> <p>I went out today and took a photo!</p> <figure> <img src="photo2.jpeg" alt="The photograph shows my squirrel feeder hanging from the edge of my roof. It is half full, but there are no squirrels around. In the background, out-of-focus trees fill the shot. The feeder is made of wood with a metal grate, and it contains peanuts. The edge of the roof is wooden too, and is painted white with light blue streaks."> <figcaption>A photograph taken blindly from my front porch.</figcaption> </figure> </article>
Sometimes the entire point of the image is that a textual
description is not available, and the user is to provide the
description. For instance, the point of a CAPTCHA image is to see
if the user can literally read the graphic. Here is one way to
mark up a CAPTCHA (note the title
attribute):
<p><label>What does this image say? <img src="captcha.cgi?id=8934" title="CAPTCHA"> <input type=text name=captcha></label> (If you cannot see the image, you can use an <a href="?audio">audio</a> test instead.)</p>
Another example would be software that displays images and asks for alternative text precisely for the purpose of then writing a page with correct alternative text. Such a page could have a table of images, like this:
<table> <thead> <tr> <th> Image <th> Description <tbody> <tr> <td> <img src="2421.png" title="Image 640 by 100, filename 'banner.gif'"> <td> <input name="alt2421"> <tr> <td> <img src="2422.png" title="Image 200 by 480, filename 'ad3.gif'"> <td> <input name="alt2422"> </table>
Notice that even in this example, as much useful information
as possible is still included in the title
attribute.
Since some users cannot use images at all
(e.g. because they have a very slow connection, or because they
are using a text-only browser, or because they are listening to
the page being read out by a hands-free automobile voice Web
browser, or simply because they are blind), the alt
attribute is only allowed to be
omitted rather than being provided with replacement text when no
alternative text is available and none can be made available, as
in the above examples. Lack of effort from the part of the author
is not an acceptable reason for omitting the alt
attribute.
Generally authors should avoid using img
elements
for purposes other than showing images.
If an img
element is being used for purposes other
than showing an image, e.g. as part of a service to count page
views, then the alt
attribute must
be the empty string.
In such cases, the width
and
height
attributes should both
be set to zero.
This section does not apply to documents that are publicly accessible, or whose target audience is not necessarily personally known to the author, such as documents on a Web site, e-mails sent to public mailing lists, or software documentation.
When an image is included in a private communication (such as an
HTML e-mail) aimed at a specific person who is known to be able to
view images, the alt
attribute may
be omitted. However, even in such cases it is strongly recommended
that alternative text be included (as appropriate according to the
kind of image involved, as described in the above entries), so that
the e-mail is still usable should the user use a mail client that
does not support images, or should the document be forwarded on to
other users whose abilities might not include easily seeing
images.
Markup generators (such as WYSIWYG authoring tools) should, wherever possible, obtain alternative text from their users. However, it is recognized that in many cases, this will not be possible.
For images that are the sole contents of links, markup generators should examine the link target to determine the title of the target, or the URL of the target, and use information obtained in this manner as the alternative text.
As a last resort, implementors should either set the alt
attribute to the empty string, under
the assumption that the image is a purely decorative image that
doesn't add any information but is still specific to the surrounding
content, or omit the alt
attribute
altogether, under the assumption that the image is a key part of the
content.
Markup generators should generally avoid using the image's own file name as the alternative text. Similarly, markup generators should avoid generating alternative text from any content that will be equally available to presentation user agents (e.g. Web browsers).
This is because once a page is generated, it will typically not be updated, whereas the browsers that later read the page can be updated by the user, therefore the browser is likely to have more up-to-date and finely-tuned heuristics than the markup generator did when generating the page.
A conformance checker must report the lack of an alt
attribute as an error unless one of
the conditions listed below applies:
title
attribute is present
and has a non-empty value (as described
above).img
element is in a figure
element that satisfies the
conditions described above.meta
element with a name
attribute whose value is an
ASCII case-insensitive match for the string "generator
". (This case does not
represent a case where the document is conforming, only that the
generator could not determine appropriate alternative text —
validators are not required to show an error in this case, because
such an error might encourage markup generators to include bogus
alternative text purely in an attempt to silence validators.
Naturally, conformance checkers may report this error; for
example, there could be a user option to report all
conformance errors even those that might be the more or less
inevitable result of using a markup generator.)This section is non-normative.
CSS and media queries can be used to construct graphical page
layouts that adapt dynamically to the user's environment, in
particular to different viewport dimensions and pixel densities. For
content, however, CSS does not help; instead, we have the
img
element's srcset
attribute. This section walks
through a sample case showing how to use this attribute.
Consider a situation where on wide screens (wider than 600 CSS
pixels) a 300×150 image named a-rectangle.png
is to be used, but on smaller
screens (600 CSS pixels and less), a smaller 100×100 image
called a-square.png
is to be used. The markup
for this would look like this:
<figure> <img src="a-rectangle.png" srcset="a-square.png 600w" alt="Barney Frank wears a suit and glasses."> <figcaption>Barney Frank, 2011</figcaption> </figure>
For details on what to put in the alt
attribute, see the earlier
sections.
The problem with this is that the user agent does not necessarily know what dimensions to use for the image when the image is loading. To avoid the layout having to be reflowed multiple times as the page is loading, CSS and CSS media queries can be used to provide the dimensions:
<figure> <style scoped> #a { width: 300px; height: 150px; } @media all and (max-width: 600px) { #a { width: 100px; height: 100px; } } </style> <img src="a-rectangle.png" srcset="a-square.png 600w" id="a" alt="Barney Frank wears a suit and glasses."> <figcaption>Barney Frank, 2011</figcaption> </figure>
Alternatively, the width
and
height
attributes can be used
to provide the width for legacy user agents, using CSS just for the
user agents that support srcset
:
<figure> <style scoped media="all and (max-width: 600px)"> #a { width: 100px; height: 100px; } </style> <img src="a-rectangle.png" width="300" height="100" srcset="a-square.png 600w" id=a alt="Barney Frank wears a suit and glasses."> <figcaption>Barney Frank, 2011</figcaption> </figure>
The srcset
attribute is used
with the src
attribute, which
gives the URL of the image to use for legacy user agents that do not
support the srcset
attribute.
This leads to a question of which image to provide in the src
attribute.
The answer that results in the least duplication is to provide the image suitable for an infinite width and infinite height viewport with a pixel density of 1 CSS pixel per device pixel:
<img src="pear-desktop.jpeg" srcset="pear-mobile.jpeg 720w, pear-tablet.jpeg 1280w" alt="The pear is juicy.">
However, if legacy mobile user agents are more important, one can
list all three images in the srcset
attribute, overriding the
src
attribute entirely. To do
this, the widest image has to have the pixel density descriptor
instead of the width, since there is no way to specify an infinite
width explicitly:
<img src="pear-mobile.jpeg" srcset="pear-mobile.jpeg 720w, pear-tablet.jpeg 1280w, pear-desktop.jpeg 1x" alt="The pear is juicy.">
Since at this point the src
attribute is actually being ignored entirely by srcset
-supporting user agents, the
src
attribute can default to any
image, including one that is neither the smallest nor biggest:
<img src="pear-tablet.jpeg" srcset="pear-mobile.jpeg 720w, pear-tablet.jpeg 1280w, pear-desktop.jpeg 1x" alt="The pear is juicy.">
The dimensions in the srcset
attribute are the maximum (viewport) dimensions that an image is
intended for. It is possible to think of the numbers as minimums,
though... if the images are listed in order, then the minimum for an
image is the dimension given for the previous image. This example
attempts to demonstrate this by using the file names to show the
minimum values for each image:
<img src="pear-tablet.jpeg" srcset="pear-min0.jpeg 720w, pear-min721.jpeg 1280w, pear-min1281.jpeg 1x" alt="The pear is juicy.">