Edition for Web Developers — Last Updated 16 January 2024
picture
elementSupport in all current engines.
source
elements, followed by one img
element,
optionally intermixed with script-supporting elements.HTMLPictureElement
.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. Also, 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.
source
elementSupport in all current engines.
picture
element, before the img
element.track
elements.type
— Type of embedded resource
media
— Applicable media
src
(in audio
or video
) — Address of the resource
srcset
(in picture
) — Images to use in different situations, e.g., high-resolution displays, small monitors, etc.
sizes
(in picture
) — Image sizes for different page layouts
width
(in picture
) — Horizontal dimension
height
(in picture
) — Vertical dimension
HTMLSourceElement
.The source
element allows authors to specify multiple alternative
source sets for img
elements or multiple alternative
media resources for media
elements. It does not represent anything on its own.
The type
attribute
may be present. If present, the value must be a valid MIME type string.
The media
attribute may also be present. If present, the value must contain a valid media query
list. The user agent will skip to the next source
element if the value does
not match the environment.
The media
attribute is only evaluated
once during the resource selection algorithm
for media elements. In contrast, when using the
picture
element, the user agent will react to
changes in the environment.
The remainder of the requirements depend on whether the parent is a picture
element or a media element:
source
element's parent is a picture
elementThe srcset
attribute must be present, and is a srcset attribute.
The srcset
attribute contributes the image sources to the source set, if the
source
element is selected.
If the srcset
attribute has any image candidate strings using a width descriptor, the
sizes
attribute may also be present. If, additionally,
the following sibling img
element does not allow
auto-sizes, the sizes
attribute must be present.
The sizes
attribute is a sizes attribute, which contributes the source size to
the source set, if the source
element is selected.
If the img
element allows auto-sizes, then the sizes
attribute can be omitted on previous sibling
source
elements. In such cases, it is equivalent to specifying auto
.
The source
element supports dimension attributes. The
img
element can use the width
and height
attributes of a source
element, instead of
those on the img
element itself, to determine its rendered dimensions and
aspect-ratio, as defined in the Rendering section.
The type
attribute 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:
A media
attribute specified with a value that,
after stripping leading and trailing
ASCII whitespace, is not the empty string and is not an ASCII
case-insensitive match for the string "all
".
A type
attribute specified.
The src
attribute must not be present.
source
element's parent is a media elementThe src
attribute
gives the URL of the media resource. The value must be a valid
non-empty URL potentially surrounded by spaces. This attribute must be present.
The type
attribute gives the type of the media
resource, to help the user agent determine if it can play this media
resource before fetching it. The codecs
parameter, which certain
MIME types define, might be necessary to specify exactly how the resource is encoded.
[RFC6381]
Dynamically modifying a source
element's src
or type
attribute
when the element is already inserted in a video
or audio
element will
have no effect. To change what is playing, just use the src
attribute on the media element directly, possibly making use of the canPlayType()
method to pick from amongst available
resources. Generally, manipulating source
elements manually after the document has
been parsed is an unnecessarily complicated approach.
The following list shows some examples of how to use the codecs=
MIME
parameter in the type
attribute.
< source src = 'video.mp4' type = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
< source src = 'video.mp4' type = 'video/mp4; codecs="avc1.58A01E, mp4a.40.2"' >
< source src = 'video.mp4' type = 'video/mp4; codecs="avc1.4D401E, mp4a.40.2"' >
< source src = 'video.mp4' type = 'video/mp4; codecs="avc1.64001E, mp4a.40.2"' >
< source src = 'video.mp4' type = 'video/mp4; codecs="mp4v.20.8, mp4a.40.2"' >
< source src = 'video.mp4' type = 'video/mp4; codecs="mp4v.20.240, mp4a.40.2"' >
< source src = 'video.3gp' type = 'video/3gpp; codecs="mp4v.20.8, samr"' >
< source src = 'video.ogv' type = 'video/ogg; codecs="theora, vorbis"' >
< source src = 'video.ogv' type = 'video/ogg; codecs="theora, speex"' >
< source src = 'audio.ogg' type = 'audio/ogg; codecs=vorbis' >
< source src = 'audio.spx' type = 'audio/ogg; codecs=speex' >
< source src = 'audio.oga' type = 'audio/ogg; codecs=flac' >
< source src = 'video.ogv' type = 'video/ogg; codecs="dirac, vorbis"' >
If the author isn't sure if user agents will all be able to render the media resources
provided, the author can listen to the error
event on the last
source
element and trigger fallback behavior:
< script >
function fallback( video) {
// replace <video> with its contents
while ( video. hasChildNodes()) {
if ( video. firstChild instanceof HTMLSourceElement)
video. removeChild( video. firstChild);
else
video. parentNode. insertBefore( video. firstChild, video);
}
video. parentNode. removeChild( video);
}
</ script >
< video controls autoplay >
< source src = 'video.mp4' type = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
< source src = 'video.ogv' type = 'video/ogg; codecs="theora, vorbis"'
onerror = "fallback(parentNode)" >
...
</ video >
img
elementSupport in all current engines.
usemap
attribute: Interactive content.picture
element, after all source
elements.alt
— Replacement text for use when images are not available
src
— Address of the resource
srcset
— Images to use in different situations, e.g., high-resolution displays, small monitors, etc.
sizes
— Image sizes for different page layouts
crossorigin
— How the element handles crossorigin requests
usemap
— Name of image map to use
ismap
— Whether the image is a server-side image map
width
— Horizontal dimension
height
— Vertical dimension
referrerpolicy
— Referrer policy for fetches initiated by the element
decoding
— Decoding hint to use when processing this image for presentation
loading
— Used when determining loading deferral
fetchpriority
— Sets the priority for fetches initiated by the element
alt
attribute: for authors; for implementers.HTMLImageElement
.An img
element represents an image.
An img
element has a dimension
attribute source, initially set to the element itself.
Support in all current engines.
Support in all current engines.
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 a separate 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 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 document element), animated bitmaps (APNGs, animated GIFs), animated vector graphics (XML files with an SVG document 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 the like. [PNG] [GIF] [JPEG] [PDF] [XML] [APNG] [SVG] [MNG]
The srcset
attribute may also be present, and is a
srcset attribute.
The srcset
attribute and the src
attribute (if width
descriptors are not used) contribute the image sources
to the source set (if no source
element was selected).
If the srcset
attribute is present and has any image candidate strings using a width
descriptor, the sizes
attribute must also be present.
If the srcset
attribute is not specified, and the
loading
attribute is in the Lazy state, the sizes
attribute may be specified with the value "auto
" (ASCII case-insensitive). The sizes
attribute is a sizes attribute,
which contributes the source size to the source set (if no
source
element was selected).
An img
element allows auto-sizes if:
loading
attribute is in the Lazy state, andsizes
attribute's value is "auto
" (ASCII case-insensitive), or starts with "auto,
" (ASCII case-insensitive).Support in all current engines.
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
.
The referrerpolicy
attribute is a referrer
policy attribute. Its purpose is to set the referrer policy used when fetching the image. [REFERRERPOLICY]
The decoding
attribute indicates the preferred method to decode this
image. The attribute, if present, must be an image decoding hint. This attribute's missing value default and invalid value default are both the auto state.
HTMLImageElement/fetchPriority
The fetchpriority
attribute is a fetch
priority attribute. Its purpose is to set the priority used when fetching the image.
The loading
attribute is a lazy
loading attribute. Its purpose is to indicate the policy for loading images that are
outside the viewport.
When the loading
attribute's state is changed to the
Eager state, the user agent must run these
steps:
Let resumptionSteps be the img
element's lazy load
resumption steps.
If resumptionSteps is null, then return.
Set the img
's lazy load resumption steps to null.
Invoke resumptionSteps.
< img src = "1.jpeg" alt = "1" >
< img src = "2.jpeg" loading = eager alt = "2" >
< img src = "3.jpeg" loading = lazy alt = "3" >
< div id = very-large ></ div > <!-- Everything after this div is below the viewport -->
< img src = "4.jpeg" alt = "4" >
< img src = "5.jpeg" loading = lazy alt = "5" >
In the example above, the images load as follows:
1.jpeg
, 2.jpeg
,
4.jpeg
The images load eagerly and delay the window's load event.
3.jpeg
The image loads when layout is known, due to being in the viewport, however it does not delay the window's load event.
5.jpeg
The image loads only once scrolled into the viewport, and does not delay the window's load event.
Developers are encouraged to specify a preferred aspect ratio via width
and height
attributes
on lazy loaded images, even if CSS sets the image's width and height properties, to prevent the
page layout from shifting around after the image loads.
The img
HTML element insertion
steps, given insertedNode, are:
If insertedNode's parent is a picture
element, then, count this as
a relevant mutation for
insertedNode.
The img
HTML element removing
steps, given removedNode and oldParent, are:
If oldParent is a picture
element, then, count this as a
relevant mutation for removedNode.
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 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 behavior when used
together with source
elements with the media
attribute specified in a picture
element.
The img
element supports dimension
attributes.
image.width [ = value ]
image.height [ = value ]
These attributes return the actual rendered dimensions of the image, or 0 if the dimensions are not known.
They can be set, to change the corresponding content attributes.
image.naturalWidth
image.naturalHeight
These attributes return the natural dimensions of the image, or 0 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.decode()
This method causes the user agent to decode the image in parallel, returning a promise that fulfills when decoding is complete.
The promise will be rejected with an "EncodingError
"
DOMException
if the image cannot be decoded.
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.
Without the decode()
method, the process of loading an
img
element and then displaying it might look like the following:
const img = new Image();
img. src = "nebula.jpg" ;
img. onload = () => {
document. body. appendChild( img);
};
img. onerror = () => {
document. body. appendChild( new Text( "Could not load the nebula :(" ));
};
However, this can cause notable dropped frames, as the paint that occurs after inserting the image into the DOM causes a synchronous decode on the main thread.
This can instead be rewritten using the decode()
method:
const img = new Image();
img. src = "nebula.jpg" ;
img. decode(). then(() => {
document. body. appendChild( img);
}). catch (() => {
document. body. appendChild( new Text( "Could not load the nebula :(" ));
});
This latter form avoids the dropped frames of the original, by allowing the user agent to decode the image in parallel, and only inserting it into the DOM (and thus causing it to be painted) once the decoding process is complete.
Because the decode()
method attempts to ensure that the
decoded image data is available for at least one frame, it can be combined with the requestAnimationFrame()
API.
This means it can be used with coding styles or frameworks that ensure that all DOM modifications
are batched together as animation frame
callbacks:
const container = document. querySelector( "#container" );
const { containerWidth, containerHeight } = computeDesiredSize();
requestAnimationFrame(() => {
container. style. width = containerWidth;
container. style. height = containerHeight;
});
// ...
const img = new Image();
img. src = "supernova.jpg" ;
img. decode(). then(() => {
requestAnimationFrame(() => container. appendChild( img));
});
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 > She 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 > She stared at the folder. S! The answer she had been looking for all
this time was simply the letter S! How had she not seen that before? It all
came together now. The phone call where Hector had referred to a lion's tail,
the time Maria had stuck her 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. She also liked to jump.</ p >
< aside >< img src = "fluffy.jpg" alt = "" title = "Fluffy" ></ aside >
< p > She would play in the morning, she would play in the evening.</ p >
</ article >