HTMLImageElement: src property
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
TheHTMLImageElement
propertysrc
, which reflects the HTMLsrc
attribute, specifies the image to display in the<img>
element.
Value
When providing only a single image, rather than a set of images from which the browserselects the best match for the viewport size and display pixel density, thesrc
attribute is a string specifying the URL of thedesired image. This can be set either within the HTML itself using thesrc
content attribute, or programmatically by setting theelement'ssrc
property.
If you use thesrcset
content attribute to provide multipleimage options for different display pixel densities, the URL specified by thesrc
attribute is used in one of two ways:
- as a fallback for browsers that don't support
srcset
. - as an equivalent for specifying an image in
srcset
with the sizemultiplier1x
; that is, the image specified bysrc
is usedon low-density screens (such as typical 72 DPI or 96 DPI displays).
Additionally, if you usesrc
along withbothsizes
(or thecorrespondingsizes
content attribute)andsrcset
in order to choose an image based on the viewport size, thesrc
attribute is only used as a fallback for browsers that don't supportsizes
andsrcset
; otherwise, it's not used at all.
Examples
Specifying a single image
HTML
<img src="grapefruit-slice-332-332.jpg" width="160" alt="Slices of grapefruit, looking yummy." />
Result
Using src with an image set
When using a set of images with thesrcset
property, thesrc
serves as either a fallback for older browsers, or as the1x
size of the image.
HTML
Result
Specifying a fallback for viewport-based selection
When using viewport-bases selection of an image from asrcset
by alsospecifying thesizes
property, thesrc
property serves as the fallback to be used on browsers that don'tsupport viewport-based selection. Browsers thatdo support viewport-basedselection will ignoresrc
in this situation.
HTML
Result
Specifications
Specification |
---|
HTML # dom-img-src |