Introduction

To embed an image in HTML, when there is only a single image resource, use the img element and its src attribute.

<h2>From today's featured article</h2>
<img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

However, there are a number of situations for which the author might wish to use multiple image resources that the user agent can choose from:

The above situations are not mutually exclusive. For example, it is reasonable to combine different resources for different device-pixel-ratio with different resources for art direction.

While it is possible to solve these problems using scripting, doing so introduces some other problems:

With this in mind, this specification introduces a number of features to address the above problems in a declarative manner.

Device-pixel-ratio-based selection when the rendered size of the image is fixed

The src and srcset attributes on the img element can be used, using the x descriptor, to provide multiple images that only vary in their size (the smaller image is a scaled-down version of the bigger image).

The x descriptor is not appropriate when the rendered size of the image depends on the viewport width (viewport-based selection), but can be used together with art direction.

<h2>From today's featured article</h2>
<img src="/uploads/100-marie-lloyd.jpg"
     srcset="/uploads/150-marie-lloyd.jpg 1.5x, /uploads/200-marie-lloyd.jpg 2x"
     alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

The user agent can choose any of the given resources depending on the user's screen's pixel density, zoom level, and possibly other factors such as the user's network conditions.

For backwards compatibility with older user agents that don't yet understand the srcset attribute, one of the URLs is specified in the img element's src attribute. This will result in something useful (though perhaps lower-resolution than the user would like) being displayed even in older user agents. For new user agents, the src attribute participates in the resource selection, as if it was specified in srcset with a 1x descriptor.

The image's rendered size is given in the width and height attributes, which allows the user agent to allocate space for the image before it is downloaded.

Viewport-based selection

The srcset and sizes attributes can be used, using the w descriptor, to provide multiple images that only vary in their size (the smaller image is a scaled-down version of the bigger image).

In this example, a banner image takes up the entire viewport width (using appropriate CSS).

<h1><img sizes="100vw" srcset="wolf-400.jpg 400w, wolf-800.jpg 800w, wolf-1600.jpg 1600w"
     src="wolf-400.jpg" alt="The rad wolf"></h1>

The user agent will calculate the effective pixel density of each image from the specified w descriptors and the specified rendered size in the sizes attribute. It can then choose any of the given resources depending on the user's screen's pixel density, zoom level, and possibly other factors such as the user's network conditions.

If the user's screen is 320 CSS pixels wide, this is equivalent to specifying wolf-400.jpg 1.25x, wolf-800.jpg 2.5x, wolf-1600.jpg 5x. On the other hand, if the user's screen is 1200 CSS pixels wide, this is equivalent to specifying wolf-400.jpg 0.33x, wolf-800.jpg 0.67x, wolf-1600.jpg 1.33x. By using the w descriptors and the sizes attribute, the user agent can choose the correct image source to download regardless of how large the user's device is.

For backwards compatibility, one of the URLs is specified in the img element's src attribute. In new user agents, the src attribute is ignored when the srcset attribute uses w descriptors.

In this example, the Web page has three layouts depending on the width of the viewport. The narrow layout has one column of images (the width of each image is about 100%), the middle layout has two columns of images (the width of each image is about 50%), and the widest layout has three columns of images, and some page margin (the width of each image is about 33%). It breaks between these layouts when the viewport is 30em wide and 50em wide, respectively.

<img sizes="(max-width: 30em) 100vw, (max-width: 50em) 50vw, calc(33vw - 100px)"
     srcset="swing-200.jpg 200w, swing-400.jpg 400w, swing-800.jpg 800w, swing-1600.jpg 1600w"
     src="swing-400.jpg" alt="Kettlebell Swing">

The sizes attribute sets up the layout breakpoints at 30em and 50em, and declares the image sizes between these breakpoints to be 100vw, 50vw, or calc(33vw - 100px). These sizes do not necessarily have to match up exactly with the actual image width as specified in the CSS.

The user agent will pick a width from the sizes attribute, using the first item with a <media-condition> (the part in parentheses) that evaluates to true, or using the last item (calc(33vw - 100px)) if they all evaluate to false.

For example, if the viewport width is 29em, then (max-width: 30em) evaluates to true and 100vw is used, so the image size, for the purpose of resource selection, is 29em. If the viewport width is instead 32em, then (max-width: 30em) evaluates to false, but (max-width: 50em) evaluates to true and 50vw is used, so the image size, for the purpose of resource selection, is 16em (half the viewport width). Notice that the slightly wider viewport results in a smaller image because of the different layout.

The user agent can then calculate the effective pixel density and choose an appropriate resource similarly to the previous example.

Art direction-based selection

The picture element and the source element, together with the media attribute, can be used, to provide multiple images that vary the image content (for instance the smaller image might be a cropped version of the bigger image).

<picture>
  <source media="(min-width: 45em)" srcset="large.jpg">
  <source media="(min-width: 32em)" srcset="med.jpg">
  <img src="small.jpg" alt="The president giving an award.">
</picture>

The user agent will choose the first source element for which the media query in the media attribute matches, and then choose an appropriate URL from its srcset attribute.

The rendered size of the image varies depending on which resource is chosen. To specify dimensions that the user agent can use before having downloaded the image, CSS can be used.

img { width: 300px; height: 300px }
@media (min-width: 32em) { img { width: 500px; height:300px } }
@media (min-width: 45em) { img { width: 700px; height:400px } }

This example combines art direction- and device-pixel-ratio-based selection. A banner that takes half the viewport is provided in two versions, one for wide screens and one for narrow screens.

<h1>
 <picture>
  <source media="(max-width: 500px)" srcset="banner-phone.jpeg, banner-phone-HD.jpeg 2x">
  <img src="banner.jpeg" srcset="banner-HD.jpeg 2x" alt="The Breakfast Combo">
 </picture>
</h1>
Image format-based selection

The type attribute on the source element can be used, to provide multiple images in different formats.

<h2>From today's featured article</h2>
<picture>
 <source srcset="/uploads/100-marie-lloyd.webp" type="image/webp">
 <source srcset="/uploads/100-marie-lloyd.jxr" type="image/vnd.ms-photo">
 <img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
</picture>
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

In this example, the user agent will choose the first source that has a type attribute with a supported MIME type. If the user agent supports WebP images, the first source element will be chosen. If not, but the user agent does support JPEG XR images, the second source element will be chosen. If neither of those formats are supported, the img element will be chosen.

Adaptive images

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 and the picture element. This section walks through a sample case showing how to use these features.

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>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" alt="Barney Frank wears a suit and glasses.">
 </picture>
 <figcaption>Barney Frank, 2011</figcaption>
</figure>

For details on what to put in the alt attribute, see the Requirements for providing text to act as an alternative for images section.

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 (max-width: 600px) { #a { width: 100px; height: 100px; } }
 </style>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" alt="Barney Frank wears a suit and glasses." id="a">
 </picture>
 <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 picture:

<figure>
 <style scoped media="(max-width: 600px)">
  #a { width: 100px; height: 100px; }
 </style>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" width="300" height="150"
  alt="Barney Frank wears a suit and glasses." id="a">
 </picture>
 <figcaption>Barney Frank, 2011</figcaption>
</figure>

The img element is used with the src attribute, which gives the URL of the image to use for legacy user agents that do not support the picture element. This leads to a question of which image to provide in the src attribute.

If the author wants the biggest image in legacy user agents, the markup could be as follows:

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <img src="pear-desktop.jpeg" alt="The pear is juicy.">
</picture>

However, if legacy mobile user agents are more important, one can list all three images in the source elements, overriding the src attribute entirely.

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <source srcset="pear-desktop.jpeg">
 <img src="pear-mobile.jpeg" alt="The pear is juicy.">
</picture>

Since at this point the src attribute is actually being ignored entirely by picture-supporting user agents, the src attribute can default to any image, including one that is neither the smallest nor biggest:

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <source srcset="pear-desktop.jpeg">
 <img src="pear-tablet.jpeg" alt="The pear is juicy.">
</picture>

Above the max-width media feature is used, giving the maximum (viewport) dimensions that an image is intended for. It is also possible to use min-width instead.

<picture>
 <source srcset="pear-desktop.jpeg" media="(min-width: 1281px)">
 <source srcset="pear-tablet.jpeg" media="(min-width: 721px)">
 <img src="pear-mobile.jpeg" alt="The pear is juicy.">
</picture>

Dependencies

Media Queries
<media-condition>
CSS Values and Units
<length>
CSS Syntax
Parse a comma-separated list of component values
component value
<whitespace-token>
Fetch
context

The picture element

Categories:
Flow content.
Phrasing content.
Embedded content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Zero or more source elements, followed by one img element, optionally intermixed with script-supporting elements.
Content attributes:
Global attributes
DOM interface:
interface HTMLPictureElement : HTMLElement {};

The picture element is a container which provides multiple sources to its contained img element to allow authors to declaratively control or give hints to the user agent about which image resource to use, based on the screen pixel density, viewport size, image format, and other factors. It represents its children.

The picture element is somewhat different from the similar-looking video and audio elements. While all of them contain source elements, the source element's src attribute has no meaning when the element is nested within a picture element, and the resource selection algorithm is different. As well, the picture element itself does not display anything; it merely provides a context for its contained img element that enables it to choose from multiple URLs.

The source element when used with the picture element

Categories:
Same as for the source element.
Contexts in which this element can be used:
As a child of a picture element, before the img element.
Content model:
Same as for the source element.
Content attributes:
Global attributes
srcset
sizes
media
type
DOM interface:
partial interface HTMLSourceElement {
           attribute DOMString srcset;
           attribute DOMString sizes;
           attribute DOMString media;
};

The authoring requirements in this section only apply if the source element has a parent that is a picture element.

The source element allows authors to specify multiple alternative source sets for img elements. It does not represent anything on its own.

The srcset attribute must be present, and must consist of one or more image candidate strings, each separated from the next by a U+002C COMMA character (,). If an image candidate string contains no descriptors and no space characters after the URL, the following image candidate string, if there is one, must begin with one or more space characters.

If the srcset attribute has any image candidate strings using a width descriptor, the sizes attribute must also be present, and the value must be a valid source size list.

The media attributes may also be present. If present, the value must contain a valid media query list.

The type attribute may also be present. If present, the value must be a valid MIME type. It gives the type of the images in the source set, to allow the user agent to skip to the next source element if it does not support the given type.

If the type attribute is not specified, the user agent will not select a different source element if it finds that it does not support the image format after fetching it.

When a source element has a following sibling source element or img element with a srcset attribute specified, it must have at least one of the following:

The src attribute must not be present.

The IDL attributes srcset, sizes and media must reflect the respective content attributes of the same name.

The img element

Categories:
Flow content.
Phrasing content.
Embedded content.
Form-associated element.
If the element has a usemap attribute: Interactive content.
Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Empty.
Content attributes:
Global attributes
alt
src
srcset
sizes
crossorigin
usemap
ismap
width
height
DOM interface:
[NamedConstructor=Image(optional unsigned long width, optional unsigned long height)]
interface HTMLImageElement : HTMLElement {
           attribute DOMString alt;
           attribute DOMString src;
           attribute DOMString srcset;
           attribute DOMString sizes;
           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;
  readonly attribute DOMString currentSrc;
};

An img element represents an image.

The image given by the src and srcset attributes, and any previous sibling source elements' srcset attributes if the parent is a picture element, 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 requirements on the alt attribute's value are described in the next section.

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 (,). If an image candidate string contains no descriptors and no space characters after the URL, the following image candidate string, if there is one, must begin with one or more space characters.

An image candidate string consists of the following components, in order, with the further restrictions described below this list:

  1. Zero or more space characters.

  2. A valid non-empty URL that does not start or end with a U+002C COMMA character (,), referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted.

  3. Zero or more space characters.

  4. Zero or one of the following:

  5. Zero or more space characters.

There must not be an image candidate string for an element that has the same width descriptor value as another image candidate string's width descriptor value for the same element.

There must not be an image candidate string for an element that has the same pixel density descriptor value as another image candidate string's pixel density descriptor value for the same element. For the purpose of this requirement, an image candidate string with no descriptors is equivalent to an image candidate string with a 1x descriptor.

If a source element has a sizes attribute present or an img element has a sizes attribute present, all image candidate strings for that element must have the width descriptor specified.

If an image candidate string for an source or img element has the width descriptor specified, all other image candidate strings for that element must also have the width descriptor specified.

The specified width in an image candidate string's width descriptor must match the intrinsic width in the resource given by the image candidate string's URL, if it has an intrinsic width.

The requirements above imply that images can 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, these definitions preclude SVG files with script, multipage PDF files, interactive MNG files, HTML documents, plain text documents, and so forth.

If the srcset attribute is present and has any image candidate strings using a width descriptor, the sizes attribute must also be present, and the value must be a valid source size list.

A valid source size list is a string that matches the following grammar:

<source-size-list> = [ <source-size># , ]? <source-size-value>
<source-size> = <media-condition> <source-size-value>
<source-size-value> = <length>

A <source-size-value> must not be negative.

Percentages are not allowed in a <source-size-value>, to avoid confusion about what it would be relative to. The vw unit can be used for sizes relative to the viewport width.

The img element must not be used as a layout tool. In particular, img elements should not be used to display transparent images, as such images 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 element has a current request and a pending request. The current request is initially set to a new image request. The pending request is initially set to null. The current request is usually referred to as the img element itself.

An image request has a state, current URL and image data.

An image request's state is one of the following:

Unavailable
The user agent hasn't obtained any image data, or has obtained some or all of the image data but hasn't yet decoded enough of the image to get the image dimensions.
Partially available
The user agent has obtained some of the image data and at least the image dimensions are available.
Completely available
The user agent has obtained all of the image data and at least the image dimensions are available.
Broken
The user agent has obtained all of the image data that it can, but it cannot even decode the image enough to get the image dimensions (e.g. the image is corrupted, or the format is not supported, or no data could be obtained).

An image request's current URL is initially the empty string.

An image request's image data is the decoded image data.

When an image request is either in the partially available state or in the completely available state, it is said to be available.

An image request is initially unavailable.

When an img element is available, it provides a paint source whose width is the image's density-corrected intrinsic width (if any), whose height is the image's density-corrected intrinsic height (if any), and whose appearance is the intrinsic appearance of the image.

In a browsing context where scripting is disabled, user agents may obtain images immediately or on demand. In a browsing context where scripting is enabled, user agents must obtain images immediately.

A user agent that obtains images immediately must synchronously update the image data of an img element, with the restart animation flag set if so stated, whenever that element is created or has experienced relevant mutations.

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 is in the unavailable state. When an img element has experienced relevant mutations, if the user agent only obtains images on demand, the img element must return to the unavailable state.

The relevant mutations for an img element are as follows:

Each img element has a last selected source, which must initially be null.

Each image request has 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. The image's density-corrected intrinsic width and height are the intrinsic width and height after taking into account 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. Each image furthermore has an ignore higher-layer caching flag. 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 Documents), but must not change the keys of entries copied in this way when doing so, and must unset the ignore higher-layer caching flag for the copied entry. User agents may also remove images from such lists at any time (e.g. to save memory). User agents must remove entries in the list of available images as appropriate given higher-layer caching semantics for the resource (e.g. the HTTP Cache-Control response header) when the ignore higher-layer caching is unset.

The list of available images is intended to enable synchronous switching when changing the src attribute to a URL that has previously been loaded, and to avoid re-downloading images in the same document even when they don't allow caching per HTTP. It is not used to avoid re-downloading the same image while the previous image is still loading, but the fetch algorithm allows the download to be reused in that case.

The user agent can also store the image data separately from the list of available images.

For example, if a resource has the HTTP response header Cache-Control: must-revalidate, the user agent would remove it from the list of available images but could keep the image data separately, and use that if the server responds with a 304 Not Modified status.

When the user agent is to update the image data of an img element, optionally with the restart animations flag set, it must run the following steps:

  1. If the element's node document is not the active document, then run these substeps:

    1. Continue running this algorithm in parallel.

    2. Wait until the element's node document is the active document.

    3. 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.

    4. Queue a microtask to continue this algorithm.

  2. If the user agent cannot support images, or its support for images has been disabled, then abort the image request for the current request and the pending request, set current request to the unavailable state, let pending request be null, and abort these steps.

  3. If the element does not have a srcset attribute specified and it does not have a parent or it has a parent but it is not a picture element, and it 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.

  4. Let the img element's last selected source be selected source.

  5. If selected source is not null, run these substeps:

    1. Resolve selected source, relative to the element, and let the result be absolute URL. If that is not successful, then abort these inner set of steps.

    2. 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 node document's origin.

    3. If the list of available images contains an entry for key, then set the ignore higher-layer caching flag for that entry, abort the image request for the current request and the pending request, let pending request be null, let current request be a new image request whose image data is that of the entry and whose state is set to the completely available state, update the presentation of the image appropriately, let the current request's current pixel density be selected pixel density, queue a task to restart the animation if restart animation is set, change current request's current URL to absolute URL, and then fire a simple event named load at the img element, and abort these steps.

  6. 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 ⌛.)

  7. ⌛ 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.

  8. ⌛ Let selected source and selected pixel density be the URL and pixel density that results from selecting an image source, respectively.

  9. ⌛ If selected source is null, run these substeps:

    1. ⌛ Set the current request to the broken state, abort the image request for the current request and the pending request, and let pending request be null.

    2. Queue a task to change the current request's current URL to the empty string, and then, if the element has a src attribute or a srcset attribute or a parent that is a picture element, fire a simple event named error at the img element.

    3. ⌛ Abort this algorithm.

  10. Queue a task to fire a progress event named loadstart at the img element.

  11. Resolve selected source, relative to the element, and let the result be absolute URL. If that is not successful, then abort the image request for the current request and the pending request, set the current request to the broken state, let pending request be null, queue a task to change the current request's current URL to absolute URL, fire a simple event named error at the img element and then fire a simple event named loadend at the img element, and abort these steps.

  12. ⌛ If the pending request is not null, and absolute URL is the same as the pending request's current URL, then abort these steps.

    ⌛ If absolute URL is the same as the current request's current URL, and current request is in the partially available state, then abort the image request for the pending request, queue a task to restart the animation if restart animation is set, and abort these steps.

    ⌛ If the pending request is not null, abort the image request for the pending request.

    ⌛ Let image request be a new image request whose current URL is absolute URL.

    ⌛ If current request is in the unavailable state or the broken state, let the current request be image request. Otherwise, let the pending request be image request.

    ⌛ Do a potentially CORS-enabled fetch of absolute URL, with the mode being the current state of the element's crossorigin content attribute, the origin being the origin of the img element's node document, and the default origin behaviour set to taint. Let this instance of the fetching algorithm be associated with image request.

    If the element has a srcset attribute or a parent that is a picture element, the fetching request's context must be set to imageset. Otherwise it must be set to image.

    This specification does not yet use the "fetch" algorithm from the WHATWG Fetch specification. It will be updated to do so in due course.

    The resource obtained in this fashion, if any, is image request'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 node 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.

    If the resource is CORS-same-origin, each task that is queued by the networking task source while the image is being fetched, if image request is the current request, must fire a progress event named progress at the img element.

  13. End the synchronous section, continuing the remaining steps in parallel, but without missing any data from the fetch algorithm.

  14. As soon as possible, jump to the first applicable entry from the following list:

    If the resource type is multipart/x-mixed-replace

    The next task that is queued by the networking task source while the image is being fetched must run the following steps:

    1. If image request is the pending request and at least one body part has been completely decoded, abort the image request for the current request, upgrade the pending request to the current request.

    2. Otherwise, if image request is the pending request and the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, abort the image request for the current request, upgrade the pending request to the current request and set the current request's state to broken.

    3. Otherwise, if image request is the current request, it is in the unavailable state, and the user agent is able to determine image request's image's width and height, set the current request's state to partially available.

    4. Otherwise, if image request is the current request, it is in the unavailable state, and the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, set the current request's state to broken.

    Each task that is queued by the networking task source while the image is being fetched must 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.

    The progress and loadend events are not fired for multipart/x-mixed-replace image streams.

    If the resource type and data corresponds to a supported image format, as described below

    The next task that is queued by the networking task source while the image is being fetched must run the following steps:

    1. If the user agent is able to determine image request's image's width and height, and image request is pending request, set image request's state to partially available.

    2. Otherwise, if the user agent is able to determine image request's image's width and height, and image request is current request, update the img element's presentation appropriately and set image request's state to partially available.

    3. Otherwise, if the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, and image request is pending request, abort the image request for the current request and the pending request, upgrade the pending request to the current request, set current request to the broken state, fire a simple event named error at the img element, fire a simple event named loadend at the img element, and abort these steps.

    4. Otherwise, if the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, and image request is current request, abort the image request for image request, fire a simple event named error at the img element, fire a simple event named loadend at the img element, and abort these steps.

    That task, and each subsequent task, that is queued by the networking task source while the image is being fetched, if image request is the current request, 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 additionally run these steps:

    1. If image request is the pending request, abort the image request for the current request, upgrade the pending request to the current request and update the img element's presentation appropriately.

    2. Set image request to the completely available state.

    3. Add the image to the list of available images using the key key, with the ignore higher-layer caching flag set.

    4. Fire a progress event or simple event named load at the img element, depending on the resource in image request.

    5. Fire a progress event or simple event named loadend at the img element, depending on the resource in image request.

    Otherwise

    The image data is not in a supported file format; the user agent must set image request to the broken state, abort the image request for the current request and the pending request, upgrade the pending request to the current request if image request is the pending request, and then queue a task to first fire a simple event named error at the img element and then fire a simple event named loadend at the img element.

To abort the image request for an image request image request means to run the following steps:

  1. Forget image request's image data, if any.

  2. Abort any instance of the fetching algorithm for image request, discarding any pending tasks generated by that algorithm.

To upgrade the pending request to the current request for an img element means to run the following steps:

  1. Let the img element's current request be the pending request.

  2. Let the img element's pending request be null.

To fire a progress event or simple event named type at an element e, depending on resource r, means to fire a progress event named type at e if r is CORS-same-origin, and otherwise fire a simple event named type at e.

While a user agent is running the above algorithm for an element x, there must be a strong reference from the element's node 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 agent 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 honour any animation in the resource.

This specification does not specify which image types are to be supported.


An img element is associated with a source set.

A source set is an ordered set of zero or more image sources and a source size.

An image source is a URL, and optionally either a density descriptor, or a width descriptor.

A source size is a <source-size-value>. When a source size has a unit relative to the viewport, it must be interpreted relative to the img element's node document's viewport. Other units must be interpreted the same as in Media Queries.

A source size must not use CSS functions other than the calc() function.

When asked to select an image source for a given img element el, user agents must do the following:

  1. Update the source set for el.

  2. If el's source set is empty, return null as the URL and undefined as the pixel density and abort these steps.

  3. Otherwise, take el's source set and let it be source set.

  4. If an entry b in source set has the same associated density descriptor as an earlier entry a in source set, then remove entry b. Repeat this step until none of the entries in source set have the same associated density descriptor as an earlier entry.

  5. In a user agent-specific manner, choose one image source from source set. Let this be selected source.

  6. Return selected source and its associated pixel density.

When asked to update the source set for a given img element el, user agents must do the following:

  1. Set el's source set to an empty source set.

  2. If el has a parent node and that is a picture element, let elements be an array containing el's parent node's child elements, retaining relative order. Otherwise, let elements be array containing only el.

  3. Iterate through elements, doing the following for each item child:

    1. If child is el:

      1. If child has a srcset attribute, parse child's srcset attribute and let the returned source set be source set. Otherwise, let source set be an empty source set.

      2. Parse child's sizes attribute and let source set's source size be the returned value.

      3. If child has a src attribute whose value is not the empty string and source set does not contain an image source with a density descriptor value of 1, and no image source with a width descriptor, append child's src attribute value to source set.

      4. Normalise the source densities of source set.

      5. Let el's source set be source set.

      6. Abort this algorithm.

    2. If child is not a source element, continue to the next child. Otherwise, child is a source element.

    3. If child does not have a srcset attribute, continue to the next child.

    4. Parse child's srcset attribute and let the returned source set be source set.

    5. If source set has zero image sources, continue to the next child.

    6. If child has a media attribute, and its value does not match the environment, continue to the next child.

    7. Parse child's sizes attribute and let source set's source size be the returned value.

    8. If child has a type attribute, and its value is an unknown or unsupported MIME type, continue to the next child.

    9. Normalise the source densities of source set.

    10. Let el's source set be source set.

    11. Abort this algorithm.

Each img element independently considers its previous sibling source elements plus the img element itself for selecting an image source, ignoring any other (invalid) elements, including other img elements in the same picture element, or source elements that are following siblings of the relevant img element.

When asked to parse a srcset attribute from an element, parse the value of the element's srcset attribute as follows:

  1. Let input be the value passed to this algorithm.

  2. Let position be a pointer into input, initially pointing at the start of the string.

  3. Let candidates be an initially empty source set.

  4. Splitting loop: Collect a sequence of characters that are space characters or U+002C COMMA characters. If any U+002C COMMA characters were collected, that is a parse error.

  5. If position is past the end of input, return candidates and abort these steps.

  6. Collect a sequence of characters that are not space characters, and let that be url.

  7. Let descriptors be a new empty list.

  8. If url ends with a U+002C COMMA character (,), follow these substeps:

    1. Remove all trailing U+002C COMMA characters from url. If this removed more than one character, that is a parse error.

    Otherwise, follow these substeps:

    1. Descriptor tokeniser: Skip whitespace

    2. Let current descriptor be the empty string.

    3. Let state be in descriptor.

    4. Let c be the character at position. Do the following depending on the value of state. For the purpose of this step, "EOF" is a special character representing that position is past the end of input.

      In descriptor

      Do the following, depending on the value of c:

      Space character

      If current descriptor is not empty, append current descriptor to descriptors and let current descriptor be the empty string. Set state to after descriptor.

      U+002C COMMA (,)

      Advance position to the next character in input. If current descriptor is not empty, append current descriptor to descriptors. Jump to the step labeled descriptor parser.

      U+0028 LEFT PARENTHESIS (()

      Append c to current descriptor. Set state to in parens.

      EOF

      If current descriptor is not empty, append current descriptor to descriptors. Jump to the step labeled descriptor parser.

      Anything else

      Append c to current descriptor.

      In parens

      Do the following, depending on the value of c:

      U+0029 RIGHT PARENTHESIS ())

      Append c to current descriptor. Set state to in descriptor.

      EOF

      Append current descriptor to descriptors. Jump to the step labeled descriptor parser.

      Anything else

      Append c to current descriptor.

      After descriptor

      Do the following, depending on the value of c:

      Space character

      Stay in this state.

      EOF

      Jump to the step labeled descriptor parser.

      Anything else

      Set state to in descriptor. Set position to the previous character in input.

      Advance position to the next character in input. Repeat this substep.

      In order to be compatible with future additions, this algorithm supports multiple descriptors and descriptors with parens.

  9. Descriptor parser: Let error be no.

  10. Let width be absent.

  11. Let density be absent.

  12. Let future-compat-h be absent.

  13. For each descriptor in descriptors, run the appropriate set of steps from the following list:

    If the descriptor consists of a valid non-negative integer followed by a U+0077 LATIN SMALL LETTER W character
    1. If the user agent does not support the sizes attribute, let error be yes.

      A conforming user agent will support the sizes attribute. However, user agents typically implement and ship features in an incremental manner in practice.

    2. If width and density are not both absent, then let error be yes.

    3. Apply the rules for parsing non-negative integers to the descriptor. If the result is zero, let error be yes. Otherwise, let width be the result.

    If the descriptor consists of a valid floating-point number followed by a U+0078 LATIN SMALL LETTER X character
    1. If width, density and future-compat-h are not all absent, then let error be yes.

    2. Apply the rules for parsing floating-point number values to the descriptor. If the result is less than zero, let error be yes. Otherwise, let density be the result.

      If density is zero, the intrinsic dimensions will be infinite. User agents are expected to have limits in how big images can be rendered, which is allowed by the hardware limitations clause.

    If the descriptor consists of a valid non-negative integer followed by a U+0068 LATIN SMALL LETTER H character

    This is a parse error.

    1. If future-compat-h and density are not both absent, then let error be yes.

    2. Apply the rules for parsing non-negative integers to the descriptor. If the result is zero, let error be yes. Otherwise, let future-compat-h be the result.

    Anything else

    Let error be yes.

  14. If future-compat-h is not absent and width is absent, let error be yes.

  15. If error is still no, then append a new image source to candidates whose URL is url, associated with a width width if not absent and a pixel density density if not absent. Otherwise, there is a parse error.

  16. Return to the step labeled splitting loop.

When asked to parse a sizes attribute from an element, parse a comma-separated list of component values from the value of the element's sizes attribute (or the empty string, if the attribute is absent), and let unparsed sizes list be the result.

For each unparsed size in unparsed sizes list:

  1. Remove all consecutive <whitespace-token>s from the end of unparsed size. If unparsed size is now empty, that is a parse error; continue to the next iteration of this algorithm.

  2. If the last component value in unparsed size is a valid non-negative <source-size-value>, let size be its value and remove the component value from unparsed size. Any CSS function other than the calc() function is invalid. Otherwise, there is a parse error; continue to the next iteration of this algorithm.

  3. Remove all consecutive <whitespace-token>s from the end of unparsed size. If unparsed size is now empty, return size and exit this algorithm. If this was not the last item in unparsed sizes list, that is a parse error.

  4. Parse the remaining component values in unparsed size as a <media-condition>. If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue to the next iteration of this algorithm.

  5. Return size and exit this algorithm.

If the above algorithm exhausts unparsed sizes list without returning a size value, return 100vw.

A parse error for the algorithms above indicates a non-fatal mismatch between input and requirements. User agents are encouraged to expose parse errors somehow.

While a valid source size list only contains a bare <source-size-value> (without an accompanying <media-condition>) as the last entry in the <source-size-list>, the parsing algorithm technically allows such at any point in the list, and will accept it immediately as the size if the preceding entries in the list weren't used. This is to enable future extensions, and protect against simple author errors such as a final trailing comma.

An image source can have a density descriptor, a width descriptor, or no descriptor at all accompanying its URL. Normalising a source set gives every image source a density descriptor.

When asked to normalise the source densities of a source set source set, the user agent must do the following:

  1. Let source size be source set's source size.

  2. For each image source in source set:

    1. If the image source has a density descriptor, continue to the next image source.

    2. Otherwise, if the image source has a width descriptor, replace the width descriptor with a density descriptor with a value of the width descriptor divided by the source size and a unit of x.

      If the source size is zero, the density would be infinity, which results in the intrinsic dimensions being zero by zero.

    3. Otherwise, give the image source a density descriptor of 1x.

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; for example, if the user is not looking at the page any more, the user agent might want to wait until the user has returned to the page before determining which image to use, in case the environment changes again in the meantime.)

User agents are encouraged to run this algorithm in particular when the user changes the viewport's size (e.g. by resizing the window or changing the page zoom), and when an img element is inserted into a document, so that the density-corrected intrinsic width and height match the new viewport, and so that the correct image is chosen when art direction is involved.

  1. 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 ⌛.)

  2. ⌛ If the img element does not have a srcset attribute specified and it either has no parent or it is not a picture element, it is not in a Document, has image data whose resource type is multipart/x-mixed-replace, or the pending request is not null, then abort this algorithm.

  3. ⌛ Let selected source and selected pixel density be the URL and pixel density that results from selecting an image source, respectively.

  4. ⌛ If selected source is null, then abort these steps.

  5. ⌛ 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.

  6. Resolve selected source, relative to the element, and let the result be absolute URL. If that is not successful, abort these steps.

  7. ⌛ Let CORS mode be the state of the element's crossorigin content attribute.

  8. ⌛ Let origin be the origin of the img element's node document.

  9. ⌛ Let key be a tuple consisting of absolute URL, CORS mode, and, if CORS mode is not No CORS, origin.

  10. ⌛ Let image request be a new image request whose current URL is absolute URL

  11. ⌛ Let the element's pending request be image request.

  12. End the synchronous section, continuing the remaining steps in parallel.

  13. If the list of available images contains an entry for key, then set image request's image data to that of the entry. Continue to the next step.

    Otherwise, do a potentially CORS-enabled fetch of absolute URL, with the mode being CORS mode, the origin being origin, 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 user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, or if the resource type is multipart/x-mixed-replace, then let pending request be null and abort these steps.

    Otherwise, wait for the fetch algorithm to queue its last task, and then continue with these steps. The resource obtained in this fashion, if any, is image request'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).

  14. Queue a task to run the following substeps:

    1. If the img element has experienced relevant mutations since this algorithm started, then let pending request be null and abort these steps.

    2. Let the img element's last selected source be selected source and the img element's current pixel density be selected pixel density.

    3. Set image request to the completely available state.

    4. Add the image to the list of available images using the key key, with the ignore higher-layer caching flag set.

    5. Upgrade the pending request to the current request.

    6. Update the img element's presentation appropriately.

    7. 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.

If the src attribute is set and the alt attribute is set to the empty string

The 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.

If the src attribute is set and the alt attribute is set to a value that isn't empty

The 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.

If the src attribute is set and the alt attribute is not

The 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:

  1. 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.

  2. 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 flow content descendants other than inter-element whitespace and the img element, then the contents of the first such figcaption element are the caption information; abort these steps.

  3. There is no caption information.

If the src attribute is not set and either the alt attribute is set to the empty string or the alt attribute is not set at all

The element represents nothing.

Otherwise

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 behaviour. 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 usemap and ismap attributes can result in confusing behaviour when used together with source elements with the media attribute specified in a picture element.

The img element supports dimension attributes.

The alt, src, srcset and sizes 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.

image . width [ = value ]
image . 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.

image . naturalWidth
image . naturalHeight

These attributes return the intrinsic dimensions of the image, or zero if the dimensions are not known.

image . complete

Returns true if the image has been completely downloaded or if no image is specified; otherwise, returns false.

image . currentSrc

Returns the image's absolute URL.

image = new 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 density-corrected intrinsic width and height of the image, in CSS pixels, if the image has intrinsic dimensions and is available but not being rendered to a visual medium; or else 0, if the image is not available or does not have intrinsic dimensions.

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 densty-corrected intrinsic width and height of the image, in CSS pixels, if the image has intrinsic dimensions and is available, or else 0.

The IDL attribute complete must return true if any of the following conditions is true:

Otherwise, the attribute must return false.

The value of complete can thus change while a script is executing.

The currentSrc IDL attribute must return the img element's current request's current URL.

A constructor is provided for creating HTMLImageElement objects (in addition to the factory methods from DOM such as createElement()): Image(width, height). When invoked as a constructor, this 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 node 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 favourite.</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>