L'elemento HTML <img>
incorpora un'immagine nel documento. È un elemento sostituito.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
L'esempio sopra mostra un uso molto semplice dell'elemento <img>
. L'attributo src
è obbligatorio e contiene il percorso dell'immagine che desideri incorporare. L'attributo alt
contiene una descrizione testuale dell'immagine, non è obbligatoria ma è incredibilmente utile per l'accessibilità - gli screen reader leggono questa descrizione ai loro utenti in modo che sappiano cosa mostra l'immagine, e viene anche visualizzata sulla pagina se l'immagine non può essere caricata per qualche motivo.
Ci sono molti altri attributi che possono essere specificati per raggiungere vari scopi, ad esempio:
- Controllo Referrer / CORS per motivi di sicurezza; vedi
crossorigin
ereferrerpolicy
. - Impostare una intrinsic size usando
width
eheight
, è utile quando si desidera impostare lo spazio occupato da un'immagine per garantire che il layout della pagina sia stabile prima che venga caricato. - Responsive image hints using
sizes
andsrcset
(see also the<picture>
element, and our Responsive images tutorial).
Formati delle immagini supportati
Lo standard HTML non fornisce un elenco di formati di immagine che devono essere supportati, quindi ogni user agent supporta un diverso set di formati.
Firefox
I formati di immagine supportati da Firefox sono:
Errori di caricamento delle immagini
Se si verifica un errore durante il tentativo di caricare o eseguire il rendering di un'immagine e un gestore di eventi onerror
è stato configurato per gestire l'evento error
tale gestore di eventi verrà chiamato. Questo può accadere in un certo numero di situazioni, tra cui:
- L'attributo
src
è vuoto onull
. - The specified
src
URL is the same as the URL of the page the user is currently on. - The specified image is corrupted in some way that prevents it from being loaded.
- The specified image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, and no dimensions were specified in the
<img>
element's attributes. - The specified image is in a format not supported by the user agent.
Attributes
This element includes the global attributes.
alt
- This attribute defines an alternative text description of the image.
Note: Browsers do not always display the image referenced by the element. This is the case for non-graphical browsers (including those used by people with visual impairments), if the user chooses not to display images, or if the browser cannot display the image because it is invalid or an unsupported type. In these cases, the browser may replace the image with the text defined in this element's
alt
attribute. You should, for these reasons and others, provide a useful value foralt
whenever possible.Note: Omitting this attribute altogether indicates that the image is a key part of the content, and no textual equivalent is available. Setting this attribute to an empty string (
alt=""
) indicates that this image is not a key part of the content (decorative), and that non-visual browsers may omit it from rendering. crossorigin
- This enumerated attribute indicates if the fetching of the related image must be done using CORS or not. CORS-enabled images can be reused in the
<canvas>
element without being "tainted." The allowed values are: -
anonymous
- A cross-origin request (i.e., with
Origin
HTTP header) is performed, but no credential is sent (i.e., no cookie, X.509 certificate, or HTTP Basic authentication). If the server does not give credentials to the origin site (by not setting theAccess-Control-Allow-Origin
HTTP header), the image will be tainted and its usage restricted. use-credentials
- A cross-origin request (i.e., with the
Origin
HTTP header) performed along with credentials sent (i.e., a cookie, certificate, or HTTP Basic authentication). If the server does not give credentials to the origin site (through theAccess-Control-Allow-Credentials
HTTP header), the image will be tainted and its usage restricted.
Origin
HTTP header), preventing its non-tainted usage in<canvas>
elements. If invalid, it is handled as if theanonymous
value was used. See CORS settings attributes for additional information. decoding
-
Provides an image decoding hint to the browser. The allowed values are:
-
sync
- Decode the image synchronously for atomic presentation with other content.
async
- Decode the image asynchronously to reduce delay in presenting other content.
auto
- Default mode, which indicates no preference for the decoding mode. The browser decides what is best for the user.
height
- The intrinsic height of the image in pixels.
importance
- Indicates the relative importance of the resource. Priority hints are delegated using the values:
-
auto
: Indicates no preference. The browser may use its own heuristics to decide the priority of the image.high
: Indicates to the browser that the image is of high priority.low
: Indicates to the browser that the image is of low priority. intrinsicsize
- This attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the size specified in the attribute. Specifically, the image would raster at these dimensions and
naturalWidth
/naturalHeight
on images would return the values specified in this attribute. Explainer, examples ismap
- This Boolean attribute indicates that the image is part of a server-side map. If so, the precise coordinates of a click are sent to the server.
referrerpolicy
- A string indicating which referrer to use when fetching the resource:
no-referrer:
TheReferer
header will not be sent.no-referrer-when-downgrade:
NoReferer
header will be sent when navigating to an origin without TLS (HTTPS). This is a user agent’s default behavior if no policy is otherwise specified.origin:
TheReferer
header will include the page of origin's scheme, the host, and the port.origin-when-cross-origin:
Navigating to other origins will limit the included referral data to the scheme, the host and the port, while navigating from the same origin will include the referrer's full path.unsafe-url:
TheReferer
header will include the origin and the path, but not the fragment, password, or username. This case is unsafe because it can leak origins and paths from TLS-protected resources to insecure origins.
sizes
- A list of one or more strings separated by commas indicating a set of source sizes. Each source size consists of:
- a media condition. This must be omitted for the last item.
- a source size value.
Source size values specify the intended display size of the image. User agents use the current source size to select one of the sources supplied by the
srcset
attribute, when those sources are described using width ('w
') descriptors. The selected source size affects the intrinsic size of the image (the image’s display size if no CSS styling is applied). If thesrcset
attribute is absent, or contains no values with a width (w
) descriptor, then thesizes
attribute has no effect. src
- The image URL. This attribute is mandatory for the
<img>
element. On browsers supportingsrcset
,src
is treated like a candidate image with a pixel density descriptor1x
unless an image with this pixel density descriptor is already defined insrcset,
or unlesssrcset
contains 'w
' descriptors. srcset
- A list of one or more strings separated by commas indicating a set of possible image sources for the user agent to use. Each string is composed of:
- a URL to an image,
- optionally, whitespace followed by one of:
- A width descriptor, or a positive integer directly followed by '
w
'. The width descriptor is divided by the source size given in thesizes
attribute to calculate the effective pixel density. - A pixel density descriptor, which is a positive floating point number directly followed by '
x
'.
- A width descriptor, or a positive integer directly followed by '
If no descriptor is specified, the source is assigned the default descriptor:
1x
.It is incorrect to mix width descriptors and pixel density descriptors in the same
srcset
attribute. Duplicate descriptors (for instance, two sources in the samesrcset
which are both described with '2x
') are also invalid.The user agent selects any one of the available sources at its discretion. This provides them with significant leeway to tailor their selection based on things like user preferences or bandwidth conditions. See our Responsive images tutorial for an example.
width
- The intrinsic width of the image in pixels.
usemap
- The partial URL (starting with '
#
') of an image map associated with the element.
Deprecated attributes
align
- The alignment of the image with respect to its surrounding context. This should no longer be used — use the
float
and/orvertical-align
CSS properties instead. You can also use theobject-position
property to position the image within the element's box. The allowed values are: -
top
- Equivalent to
vertical-align: top;
orvertical-align: text-top;
middle
- Equivalent to
vertical-align: -moz-middle-with-baseline;
bottom
- The missing value default, equivalent to
vertical-align: unset;
orvertical-align: initial;
left
- Equivalent to
float: left;
right
- Equivalent to
float: right;
border
- The width of a border around the image. You should use the
border
CSS property instead. hspace
- The number of pixels of white space to insert to the left and right of the image. You should use the
margin
CSS property instead. longdesc
- A link to a more detailed description of the image. Possible values are a URL or an element
id
.Note: This attribute is mentioned in the latest W3C version, HTML 5.2, but has been removed from the WHATWG’s HTML Living Standard. It has an uncertain future; authors should use a WAI-ARIA alternative such as
aria-describedby
oraria-details
. name
- A name for the element. You should use the
id
attribute instead. vspace
- The number of pixels of white space to insert above and below the image. You should use the
margin
CSS property instead.
Styling with CSS
<img>
is a replaced element; it has a display
value of inline
by default, but its default dimensions are defined by the embedded image's intrinsic values. You can set properties like border
/border-radius
, padding
/margin
, width
/height
, etc. on an image.
Often however it is a good idea to set images to display: block;
so that you have maximum control over the styling (e.g. margin: 0 auto
doesn't work on inline images, and it is easier to place images in context with surrounding elements when they are block-level).
<img>
has no baseline, so when images are used in an inline formatting context with vertical-align
: baseline
, the bottom of the image will be placed on the container's baseline.
You can use the object-position
property to position the image within the element's box, and the object-fit
property to adjust the sizing of the image within the box (for example, whether the image should fit the box or fill it even if clipping is required).
Depending on its type, an image may have an intrinsic width and height. For some image types, however, intrinsic dimensions are not necessary. SVG images, for instance, may have no intrinsic dimensions if their root <svg>
element doesn't have a width
or height
set on it.
Examples
Alternative text
The following simple example embeds an image into the page, and includes alternative text to improve accessibility.
<img src="https://developer.cdn.mozilla.net/media/img/mdn-logo-sm.png" alt="MDN logo — a dinosaur logo with the text MDN">
Image link
This example builds upon the previous one, showing how to turn the image into a link. It is very simple to do so — you just nest the <img>
tag inside the <a>
. One consideration is that you should made the alternative text describe the resource the link is pointing to.
<a href="https://developer.mozilla.org"> <img src="https://developer.cdn.mozilla.net/media/img/mdn-logo-sm.png" alt="Visit the MDN site"> </a>
Using the srcset attribute
In this example we include a srcset
attribute containing a reference to a high-resolution version of the logo; this will be loaded instead of the src
image on high-resolution devices. The image referenced in the src
attribute is counted as a 1x
candidate in user agents that support srcset
.
<img src="mdn-logo-sm.png" alt="MDN" srcset="mdn-logo-HD.png 2x">
Using the srcset and sizes attributes
The src
attribute is ignored in user agents that support srcset
when 'w
' descriptors are included. When the (max-width: 600px)
media condition matches, the 200px wide image will be loaded (it is the one that matches 200px most closely), otherwise the other image will be loaded.
<img src="clock-demo-thumb-200.png" alt="Clock" srcset="clock-demo-thumb-200.png 200w, clock-demo-thumb-400.png 400w" sizes="(max-width: 600px) 200px, 50vw">
Security and privacy concerns
Although <img>
elements have many innocent uses, they can have undesirable consequences for user security and privacy. See Referer header: privacy and security concerns for more information and mitigations.
Accessibility concerns
Authoring meaningful alternate descriptions
An alt
attribute's value should clearly and concisely describe the image's content. It should not describe the presence of the image itself, or the file name of the image. If the alt
attribute is purposefully left off because the image has no textual equivalent, consider alternate methods for presenting the content the image is trying to communicate.
Don't
<img alt="image" src="penguin.jpg">
Do
<img alt="A Rockhopper Penguin standing on a beach." src="penguin.jpg">
When an alt
attribute is not present on an image, some screen readers may announce the image's file name instead. This can be a confusing experience if the file name isn't representative of the image's contents.
- An alt Decision Tree • Images • WAI Web Accessibility Tutorials
- Alt-texts: The Ultimate Guide — Axess Lab
- How to Design Great Alt Text: An Introduction | Deque
- MDN Understanding WCAG, Guideline 1.1 explanations
- Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0
The title attribute
The title
attribute is not an acceptable substitute for an alt
attribute. Additionally, avoid duplicating the alt
attribute's value in a title
attribute declared on the same image. Doing so may cause some screen readers to announce the description twice, creating a confusing experience.
The title
attribute should also not be used as supplemental captioning information to accompany an image's alt
description. If an image needs a caption, use a combination of the figure
and figcaption
elements.
Technical summary
Content categories | Flow content, phrasing content, embedded content, palpable content. If the element has a usemap attribute, it also is a part of the interactive content category. |
---|---|
Permitted content | None, it is an empty element. |
Tag omission | Must have a start tag and must not have an end tag. |
Permitted parents | Any element that accepts embedded content. |
Permitted ARIA roles | Any |
DOM interface | HTMLImageElement |
Specifiche
Specifica | Stato | Commento |
---|---|---|
Referrer Policy The definition of 'referrer attribute' in that specification. |
Candidate Recommendation | Aggiunto l'attributo referrerpolicy . |
HTML Living Standard The definition of '<img>' in that specification. |
Living Standard | |
HTML5 The definition of '<img>' in that specification. |
Recommendation | |
HTML 4.01 Specification The definition of '<img>' in that specification. |
Recommendation |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
img | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
align | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
alt | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
border | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
crossorigin | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
decoding | Chrome Full support Yes | Edge ? | Firefox Full support 63 | IE No support No | Opera Full support Yes | Safari No support No | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 63 | Opera Android Full support Yes | Safari iOS No support No | Samsung Internet Android Full support Yes |
height | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
hspace | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
intrinsicsize | Chrome
Full support
71
| Edge ? | Firefox ? | IE No support No | Opera Full support 58 | Safari No support No | WebView Android
Full support
71
| Chrome Android
Full support
71
| Firefox Android ? | Opera Android Full support 50 | Safari iOS No support No | Samsung Internet Android
Full support
10.0
|
ismap | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
longdesc | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
name | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
onerror | Chrome Full support Yes | Edge ? | Firefox Full support 51 | IE ? | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 51 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
referrerpolicy | Chrome Full support 51 | Edge No support No | Firefox Full support 50 | IE No support No | Opera Full support 38 | Safari Full support 11.1 | WebView Android Full support 51 | Chrome Android Full support 51 | Firefox Android Full support 50 | Opera Android Full support 41 | Safari iOS No support No | Samsung Internet Android Full support 7.2 |
sizes | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
src | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
srcset | Chrome Full support 34 | Edge Full support Yes | Firefox
Full support
38
| IE No support No | Opera Full support 21 | Safari Full support 8 | WebView Android Full support 37 | Chrome Android Full support 34 | Firefox Android
Full support
38
| Opera Android Full support 21 | Safari iOS Full support 8 | Samsung Internet Android Full support 2.0 |
usemap | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
vspace | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
width | Chrome Full support Yes | Edge Full support Yes | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
Legend
- Full support
- Full support
- No support
- No support
- Compatibility unknown
- Compatibility unknown
- Experimental. Expect behavior to change in the future.
- Experimental. Expect behavior to change in the future.
- Non-standard. Expect poor cross-browser support.
- Non-standard. Expect poor cross-browser support.
- Deprecated. Not for use in new websites.
- Deprecated. Not for use in new websites.
- User must explicitly enable this feature.
- User must explicitly enable this feature.
Vedi anche
- Immagini nell'HTML
- Immagini responsive
<picture>
,<object>
and<embed>
elements- Other image-related CSS properties:
object-fit
,object-position
,image-orientation
,image-rendering
, andimage-resolution
.