DEV Community

Cover image for HTML tags | img
Carlos Espada
Carlos Espada

Posted on • Updated on

HTML tags | img

It is used to embed an image into the document.

The HTML standard doesn't list what image formats to support, so user agents may support different formats.

The image file formats that are most commonly used on the web are:

  • APNG (Animated Portable Network Graphics): good choice for lossless animation sequences (GIF is less performant).
  • AVIF (AV1 Image File Format): good choice for both images and animated images due to high performance.
  • GIF (Graphics Interchange Format): good choice for simple images and animations.
  • JPEG (Joint Photographic Expert Group): good choice for lossy compression of still images (currently the most popular).
  • PNG (Portable Network Graphics): good choice for lossy compression of still images (slightly better quality than JPEG).
  • SVG (Scalable Vector Graphics): vector image format. Use for images that must be drawn accurately at different sizes.
  • WebP (Web Picture): excellent choice for both images and animated images.

Formats like WebP and AVIF are highly recommended as they are now broadly (and somewhat deeply) supported by web browsers, and perform much better than PNG, JPEG, GIF for both still and animated images. SVG remains the recommended format for images that must be drawn accurately at different sizes.

Image loading errors

If an error occurs while loading or rendering an image, and an onerror event handler has been set on the error event, that event handler will get called. This can happen in a number of situations, including:

  • The src attribute is empty ("") or null.
  • The src URL is the same as the URL of the page the user is currently on.
  • The image is corrupted in some way that prevents it from being loaded.
  • The 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 image is in a format not supported by the user agent.

Attributes

alt

Defines an alternative text description of the image. It isn't mandatory but is incredibly useful for accessibility — screen readers read this description out to their users so they know what the image means.

Browsers do not always display images. There are a number of situations in which a browser might not display images, such as:

  • Non-visual browsers (such as those used by people with visual impairments).
  • The user chooses not to display images (saving bandwidth, privacy reasons)
  • The image is invalid or an unsupported type

In these cases, the browser may replace the image with the text in the element's alt attribute. For these reasons and others, provide a useful value for alt whenever possible.

Omitting alt 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 (it’s decoration or a tracking pixel), and that non-visual browsers may omit it from rendering. Visual browsers will also hide the broken image icon if the alt is empty and the image failed to display.

This attribute is also used when copying and pasting the image to text, or saving a linked image to a bookmark.

crossorigin

Indicates if the fetching of the image must be done using a CORS request. Image data from a CORS-enabled image returned from a CORS request can be reused in the <canvas> element without being marked "tainted".

If the crossorigin attribute is not specified, then a non-CORS request is sent (without the Origin request header), and the browser marks the image as tainted and restricts access to its image data, preventing its usage in <canvas> elements.

If the crossorigin attribute is specified, then a CORS request is sent (with the Origin request header); but if the server does not opt into allowing cross-origin access to the image data by the origin site (by not sending any Access-Control-Allow-Origin response header, or by not including the site's origin in any Access-Control-Allow-Origin response header it does send), then the browser blocks the image from loading, and logs a CORS error to the devtools console.

Allowed values:

  • anonymous: a CORS request is sent with credentials omitted (that is, no cookies, X.509 certificates, or Authorization request header).
  • use-credentials: the CORS request is sent with any credentials included (that is, cookies, X.509 certificates, and the Authorization request header). If the server does not opt into sharing credentials with the origin site (by sending back the Access-Control-Allow-Credentials: true response header), then the browser marks the image as tainted and restricts access to its image data.

If the attribute has an invalid value, browsers handle it as if the anonymous value was used.

decoding

Provides an image decoding hint to the browser. Allowed values:

  • 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): no preference for the decoding mode. The browser decides what is best for the user.

height

The intrinsic height of the image, in pixels. Must be an integer without a unit. Allows image to take up space before it loads, to mitigate content layout shifts.

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.

ismap

This Boolean attribute indicates that the image is part of a server-side map. If so, the coordinates where the user clicked on the image are sent to the server.

This attribute is allowed only if the <img> element is a descendant of an <a> element with a valid href attribute. This gives users without pointing devices a fallback destination.

loading

Indicates how the browser should load the image:

  • eager (default): loads the image immediately, regardless of whether or not the image is currently within the visible viewport.
  • lazy: defers loading the image until it reaches a calculated distance from the viewport, as defined by the browser. The intent is to avoid the network and storage bandwidth needed to handle the image until it's reasonably certain that it will be needed. This generally improves the performance of the content in most typical use cases.

Loading is only deferred when JavaScript is enabled. This is an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user's approximate scroll position throughout a session, by strategically placing images in a page's markup such that a server can track how many images are requested and when.

referrerpolicy

A string indicating which referrer to use when fetching the resource:

  • no-referrer: the Referer header will not be sent.
  • no-referrer-when-downgrade: the Referer header will not be sent to origins without TLS (HTTPS).
  • origin: the sent referrer will be limited to the origin of the referring page: its scheme, host and port.
  • origin-when-cross-origin: the referrer sent to other origins will be limited to the scheme, the host and the port. Navigations on the same origin will still include the path.
  • same-origin: a referrer will be sent for same origin, but cross-origin requests will contain no referrer information.
  • strict-origin: only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP).
  • strict-origin-when-cross-origin (default): send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
  • unsafe-url: the referrer will include the origin and the path (but not the fragment, password or username). This value is unsafe, because it leaks origins and paths from TLS-protected resources to insecure origins.

sizes

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 in the list.
  • A source size value.

Media Conditions describe properties of the viewport, not of the image. For example, (max-height: 500px) 1000px proposes to use a source of 1000px width, if the viewport is not higher than 500px.

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 the srcset attribute is absent, or contains no values with a width descriptor, then the sizes attribute has no effect.

src

The image URL. Mandatory for the <img> element. On browsers supporting srcset, src is treated like a candidate image with a pixel density descriptor 1x, unless an image with this pixel density descriptor is already defined in srcset, or unless srcset contains w descriptors.

srcset

One or more strings separated by commas, indicating 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 (a positive integer directly followed by w). The width descriptor is divided by the source size given in the sizes attribute to calculate the effective pixel density.
    • A pixel density descriptor (a positive floating point number directly followed by x).

If no descriptor is specified, the source is assigned the default descriptor of 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 same srcset which are both described with 2x) are also invalid.

The user agent selects any 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.

width

The intrinsic width of the image in pixels. Must be an integer without a unit. Allows image to take up space before it loads, to mitigate content layout shifts.

usemap

The partial URL (starting with #) of an image map associated with the element.

You cannot use this attribute if the <img> element is inside an <a> or <button> element.

Styling

<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, like it were inline-block. You can set properties like border/border-radius, padding/margin, width, height, etc. on an image.

<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 text 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 unnecessary. SVG images, for instance, have no intrinsic dimensions if their root <svg> element doesn't have a width or height set on it.

Accessibility

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 to present what the image is trying to communicate.

Don't

<img alt="image" src="penguin.jpg">
Enter fullscreen mode Exit fullscreen mode

Do

<img alt="A Rockhopper Penguin standing on a beach." src="penguin.jpg">
Enter fullscreen mode Exit fullscreen mode

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.

The title attribute is not an acceptable substitute for the 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 the <figure> and <figcaption> elements.

The value of the title attribute is usually presented to the user as a tooltip, which appears shortly after the cursor stops moving over the image. While this can provide additional information to the user, you should not assume that the user will ever see it: the user may only have keyboard or touchscreen. If you have information that's particularly important or valuable for the user, present it inline using one of the methods mentioned above instead of using title.

It has an implicit ARIA role img (with non-empty alt attribute or no alt attribute) or no corresponding role (with empty alt attribute).

  • Type: inline
  • Self-closing: Yes
  • Semantic value: No

Definition and example | Support

Top comments (0)