Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

<img>: The Image Embed element

BaselineWidely available *

The<img>HTML element embeds an image into the document.

Try it

<img   src="/shared-assets/images/examples/grapefruit-slice.jpg"  alt="Grapefruit slice atop a pile of other slices" />
.fit-picture {  width: 250px;}

The above example shows usage of the<img> element:

  • Thesrc attribute holds the path to the image you want to embed. It is not mandatory if thesrcset attribute is available. However, at least one of thesrc orsrcset attributes must be provided.
  • Thealt attribute holds a textual replacement for the image, which is mandatory andincredibly useful for accessibility — screen readers read the attribute value out to their users so they know what the image means. Alt text is also displayed on the page if the image can't be loaded for some reason: for example, network errors, content blocking, or link rot.

There are many other attributes to achieve various purposes:

Supported image formats

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

Note:TheImage file type and format guide provides comprehensive information about image formats and their web browser support.This section is just a summary!

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

Formats likeWebP andAVIF are recommended as they 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 anonerror event handler has been set for theerror event, that event handler will get called. This can happen in several situations, including:

  • Thesrc orsrcset attributes are empty ("") ornull.
  • ThesrcURL 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 theuser agent.

Attributes

This element includes theglobal attributes.

alt

Defines text that can replace the image in the page.

Note: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 anunsupported type

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

Setting this attribute to an empty string (alt="") indicates that this image isnot a key part of the content (it's decoration or a tracking pixel), and that non-visual browsers may omit it fromrendering. Visual browsers will also hide the broken image icon if thealt attribute 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.

attributionsrcExperimental

Specifies that you want the browser to send anAttribution-Reporting-Eligible header along with the image request.

On the server-side this is used to trigger sending anAttribution-Reporting-Register-Source orAttribution-Reporting-Register-Trigger header in the response, to register an image-basedattribution source orattribution trigger, respectively. Which response header should be sent back depends on the value of theAttribution-Reporting-Eligible header that triggered the registration.

The corresponding source or trigger event is set off once the browser receives the response containing the image file.

Note:See theAttribution Reporting API for more details.

There are two versions of this attribute that you can set:

  • Boolean, i.e., just theattributionsrc name. This specifies that you want theAttribution-Reporting-Eligible header sent to the same server as thesrc attribute points to. This is fine when you are handling the attribution source or trigger registration on the same server. When registering an attribution trigger this property is optional, and a boolean value will be used if it is omitted.
  • Value containing one or more URLs, for example:
html
<img  src="image-file.png"  alt="My image file description"  attributionsrc="https://a.example/register-source                     https://b.example/register-source" />

This is useful in cases where the requested resource is not on a server you control, or you just want to handle registering the attribution source on a different server. In this case, you can specify one or more URLs as the value ofattributionsrc. When the resource request occurs theAttribution-Reporting-Eligible header will be sent to the URL(s) specified inattributionSrc in addition to the resource origin. These URLs can then respond with aAttribution-Reporting-Register-Source orAttribution-Reporting-Register-Trigger header as appropriate to complete registration.

Note:Specifying multiple URLs means that multiple attribution sources can be registered on the same feature. You might for example have different campaigns that you are trying to measure the success of, which involve generating different reports on different data.

crossorigin

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

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

If thecrossorigin attributeis specified, then a CORS request is sent (with theOrigin 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 anyAccess-Control-Allow-Origin response header, or by not including the site's origin in anyAccess-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, nocookies,X.509 certificates, orAuthorization request header).

use-credentials

The CORS request is sent with any credentials included (that is, cookies, X.509 certificates, and theAuthorization request header). If the server does not opt into sharing credentials with the origin site (by sending back theAccess-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 theanonymous value was used. SeeCORS settings attributes for additional information.

decoding

This attribute provides a hint to the browser as to whether it should perform image decoding along with rendering the other DOM content in a single presentation step that looks more "correct" (sync), or render and present the other DOM content first and then decode the image and present it later (async). In practice,async means that the next paint does not wait for the image to decode.

It is often difficult to perceive any noticeable effect when usingdecoding on static<img> elements. They'll likely be initially rendered as empty images while the image files are fetched (either from the network or from the cache) and then handled independently anyway, so the "syncing" of content updates is less apparent. However, the blocking of rendering while decoding happens, while often quite small,can be measured — even if it is difficult to observe with the human eye. SeeWhat does the image decoding attribute actually do? for a more detailed analysis (tunetheweb.com, 2023).

Using differentdecoding types can result in more noticeable differences when dynamically inserting<img> elements into the DOM via JavaScript — seeHTMLImageElement.decoding for more details.

Allowed values:

sync

Decode the image synchronously along with rendering the other DOM content, and present everything together.

async

Decode the image asynchronously, after rendering and presenting the other DOM content.

auto

No preference for the decoding mode; the browser decides what is best for the user. This is the default value.

elementtiming

Marks the image for observation by thePerformanceElementTiming API. The value given becomes an identifier for the observed image element. See also theelementtiming attribute page.

fetchpriority

Provides a hint of the relative priority to use when fetching the image.Allowed values:

high

Fetch the image at a high priority relative to other images.

low

Fetch the image at a low priority relative to other images.

auto

Don't set a preference for the fetch priority.This is the default.It is used if no value or an invalid value is set.

SeeHTMLImageElement.fetchPriority for more information.

height

The intrinsic height of the image, in pixels. Must be an integer without a unit.

Note:Includingheight andwidth enables theaspect ratio of the image to be calculated by the browser prior to the image being loaded. This aspect ratio is used to reserve the space needed to display the image, reducing or even preventing a layout shift when the image is downloaded and painted to the screen. Reducing layout shift is a major component of good user experience and web performance.

ismap

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

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

loading

Indicates how the browser should load the image:

eager

Loads the image immediately, regardless of whether or not the image is currently within the visible viewport (this is the default value).

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.

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

Note:Images withloading set tolazy will never be loaded if they do not intersect a visible part of an element, even if loading them would change that as unloaded images have awidth andheight of0. Puttingwidth andheight on lazy-loaded images fixes this issue and is a best practice,recommended by the specification. Doing so also helps prevent layout shifts.

referrerpolicy

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

  • no-referrer: TheReferer header will not be sent.
  • no-referrer-when-downgrade: TheReferer header will not be sent toorigins withoutTLS (HTTPS).
  • origin: The sent referrer will be limited to the origin of the referring page: itsscheme,host, andport.
  • 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 forsame 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 originand the path (but not thefragment,password, orusername).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:

  1. Amedia condition. This must be omitted for the last item in the list.
  2. A source size value.

Media Conditions describe properties of theviewport, not of theimage. For example,(height <= 500px) 1000px proposes to use a source of 1000px width, if theviewport is not higher than 500px. Because a source size descriptor is used to specify the width to use for the image during layout of the page, the media condition is typically (but not necessarily) based on thewidth information.

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 thesrcset attribute, when those sources are described using width (w) descriptors. The selected source size affects theintrinsic size of the image (the image's display size if noCSS styling is applied). If thesrcset attribute is absent, or contains no values with a width descriptor, then thesizes attribute has no effect.

A source size value can be any non-negativelength. It must not use CSS functions other than themath functions. Units are interpreted in the same way asmedia queries, meaning that all relative length units are relative to the document root rather than the<img> element, so anem value is relative to the root font size, rather than the font size of the image.Percentage values are not allowed.

Thesizes attribute also accepts the following keyword values:

auto

auto can replace the whole list of sizes or the first entry in the list. It is only valid when combined withloading="lazy", and resolves to theconcrete size of the image. Since the intrinsic size of the image is not yet known,width andheight attributes (or CSS equivalents) should also be specified toprevent the browser assuming a default width of 300px.

src

The imageURL. Mandatory for the<img> element. Onbrowsers 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 containsw descriptors.

srcset

One or more strings separated by commas, indicating possible image sources for theuser agent to use. Each string is composed of:

  1. AURL to an image
  2. Optionally, whitespace followed by one of:
    • A width descriptor (a positive integer directly followed byw). The width descriptor is divided by the source size given in thesizes attribute to calculate the effective pixel density.
    • A pixel density descriptor (a positive floating point number directly followed byx).

If no descriptor is specified, the source is assigned the default descriptor of1x.

It is incorrect to mix width descriptors and pixel density descriptors in the samesrcset attribute. Duplicate descriptors (for instance, two sources in the samesrcset which are both described with2x) are also invalid.

If thesrcset attribute uses width descriptors, thesizes attribute must also be present, or thesrcset itself will be ignored.

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 orbandwidth conditions. See ourResponsive images tutorial for an example.

width

The intrinsic width of the image in pixels. Must be an integer without a unit.

usemap

The partialURL (starting with#) of animage map associated with the element.

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

Deprecated attributes

alignDeprecated

Aligns the image with its surrounding context. Use thefloat and/orvertical-alignCSS properties instead of this attribute. Allowed values:

top

Equivalent tovertical-align: top orvertical-align: text-top

middle

Equivalent tovertical-align: -moz-middle-with-baseline

bottom

The default, equivalent tovertical-align: unset orvertical-align: initial

left

Equivalent tofloat: left

right

Equivalent tofloat: right

borderDeprecated

The width of a border around the image. Use theborderCSS property instead.

hspaceDeprecated

The number of pixels of white space on the left and right of the image. Use themargin CSS property instead.

longdescDeprecated

A link to a more detailed description of the image. Possible values are aURL or an elementid.

Note:This attribute is considered obsolete in theHTML spec. It has an uncertain future; authors should use aWAI-ARIA alternative such asaria-describedby oraria-details.

nameDeprecated

A name for the element. Use theid attribute instead.

vspaceDeprecated

The number of pixels of white space above and below the image. Use themargin CSS property instead.

Styling with CSS

<img> is areplaced element; it has adisplay value ofinline by default, but its default dimensions are defined by the embedded image's intrinsic values, like it wereinline-block. You can set properties likeborder/border-radius,padding/margin,width,height, etc. on an image.

<img> has no baseline, so when images are used in an inline formatting context withvertical-align: baseline, the bottom of the image will be placed on the text baseline.

You can use theobject-position property to position the image within the element's box, and theobject-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 awidth orheight set on it.

Accessibility

Authoring meaningful alternate descriptions

Analt attribute's value should provide a clear and concise text replacement for the image's content. It should not describe the presence of the image itself or the file name of the image. If thealt 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

html
<img alt="image" src="penguin.jpg" />

Do

html
<img alt="A Penguin on a beach." src="penguin.jpg" />

An important accessibility test is to read thealt attribute content together with preceding textual content to see if it conveys the same meaning as the image. For example, if the image was preceded by the sentence "On my travels, I saw a cute little animal:", theDon't example could be read by a screen reader as "On my travels, I saw a cute little animal: image", which doesn't make sense. TheDo example could be read by a screen reader as "On my travels, I saw a cute little animal: A Penguin on a beach.", which does make sense.

For images used to trigger an action, for example, images nested inside an<a> or<button> element, consider describing the triggered action inside thealt attribute value. For example, you could writealt="next page" instead ofalt="arrow right". You could also consider adding an optional further description inside atitle attribute; this may be read by screen readers if requested by the user.

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

Identifying SVG as an image

Due to aVoiceOver bug, VoiceOver does not correctly announce SVG images as images. Includerole="img" to all<img> elements with SVG source files to ensure assistive technologies correctly announce the SVG as image content.

html
<img src="mdn.svg" alt="MDN" role="img" />

The title attribute

Thetitle attribute is not an acceptable substitute for thealt attribute. Additionally, avoid duplicating thealt attribute's value in atitle attribute declared on the same image. Doing so may cause some screen readers to announce the same text twice, creating a confusing experience.

Thetitle attribute should also not be used as supplemental captioning information to accompany an image'salt description. If an image needs a caption, use thefigure andfigcaption elements.

The value of thetitle attribute is usually presented to the user as a tooltip, which appears shortly after the cursor stops moving over the image. While thiscan 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 usingtitle.

Examples

Alternative text

The following example embeds an image into the page and includes alternative text for accessibility.

html
<img src="/shared-assets/images/examples/favicon144.png" alt="MDN" />

Image link

This example builds upon the previous one, showing how to turn the image into a link. To do so, nest the<img> tag inside the<a>. You should make the alternative text describe the resource the link is pointing to, as if you were using a text link instead.

html
<a href="https://developer.mozilla.org">  <img    src="/shared-assets/images/examples/favicon144.png"    alt="Visit the MDN site" /></a>

Using the srcset attribute

In this example we include asrcset attribute with a reference to a high-resolution version of the logo; this will be loaded instead of thesrc image on high-resolution devices. The image referenced in thesrc attribute is counted as a1x candidate inuser agents that supportsrcset.

html
<img  src="/shared-assets/images/examples/favicon72.png"  alt="MDN"  srcset="/shared-assets/images/examples/favicon144.png 2x" />

Using the srcset and sizes attributes

Thesrc attribute is ignored inuser agents that supportsrcset whenw descriptors are included. When the(width <= 600px) media condition matches, the 200 pixel-wide image will load (it is the one that matches200px most closely), otherwise the other image will load.

html
<img  src="clock-demo-200px.png"  alt="The time is 12:45."  srcset="clock-demo-200px.png 200w, clock-demo-400px.png 400w"  sizes="(width <= 600px) 200px, 50vw" />

Note:To see the resizing in action,view the example on a separate page, so you can actually resize the content area.

Security and privacy concerns

Although<img> elements have innocent uses, they can have undesirable consequences for user security and privacy. SeeReferer header: privacy and security concerns for more information and mitigations.

Technical summary

Content categoriesFlow content,phrasing content,embedded content,palpable content. If the element has ausemap attribute, it also is a part of the interactive content category.
Permitted contentNone; it is avoid element.
Tag omissionMust have a start tag and must not have an end tag.
Permitted parentsAny element that accepts embedded content.
Implicit ARIA role
  • with non-emptyalt attribute or noalt attribute:img
  • with emptyalt attribute:presentation
Permitted ARIA roles
DOM interfaceHTMLImageElement

Specifications

Specification
HTML
# the-img-element

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp