<img>:图像嵌入元素

您正在阅读此内容的英文版本,因为该语系尚未翻译。 帮助我们翻译此文章吧!

HTML <img> 元素将一份图像嵌入文档。

上面的示例展示了 <img> 元素的基本用法:

  • src 属性是必须的,它包含了你想嵌入的图片的文件路径。
  • alt 属性包含一条对图像的文本描述,这不是强制性的,但对可访问性而言,它难以置信地有用——屏幕阅读器会将这些描述读给需要使用阅读器的使用者听,让他们知道图像的含义。如果由于某种原因无法加载图像,普通浏览器也会在页面上显示alt 属性中的备用文本:例如,网络错误、内容被屏蔽或链接过期时。

还有很多其他属性,可以实现各种不同的目的:

支持的图像格式

HTML 标准并没有给出需要支持的图像格式的列表,因此每个用户代理支持一组不同的格式。A complete guide to image formats supported by web browsers is available.

Abbreviation File format MIME type File extension(s) Browser compatibility
APNG Animated Portable Network Graphics image/apng .apng Chrome, Edge, Firefox, Opera, Safari
BMP Bitmap file image/bmp .bmp Chrome, Edge, Firefox, Internet Explorer, Opera, Safari
GIF Graphics Interchange Format image/gif .gif Chrome, Edge, Firefox, Internet Explorer, Opera, Safari
ICO Microsoft Icon image/x-icon .ico, .cur Chrome, Edge, Firefox, Internet Explorer, Opera, Safari
JPEG Joint Photographic Expert Group image image/jpeg .jpg, .jpeg, .jfif, .pjpeg, .pjp Chrome, Edge, Firefox, Internet Explorer, Opera, Safari
PNG Portable Network Graphics image/png .png Chrome, Edge, Firefox, Internet Explorer, Opera, Safari
SVG Scalable Vector Graphics image/svg+xml .svg Chrome, Edge, Firefox, Internet Explorer, Opera, Safari
TIFF Tagged Image File Format image/tiff .tif, .tiff None built-in; add-ons required
WebP Web Picture format image/webp .webp Chrome, Edge, Firefox, Opera

The abbreviation for each format links to a longer description of the format, its capabilities, and detailed browser compatibility information; including which versions introduced support and specific special features that may have been introduced later.

图像加载错误

如果在加载或渲染图像时发生错误,且设置了至少一个 onerror 事件处理器来处理 error 事件,那么设置的事件处理器就会被调用。这样的错误可能发生在各种不同的情况下,包括:

  • src 属性的属性值为空("")或者 null
  • src 属性的 URL 和用户正在浏览的页面的 URL 完全相同。
  • 图像出于某些原因损坏了,从而无法加载。
  • 图像的元数据被破坏了,无法检索它的分辨率/宽高,而且在 <img> 元素的属性中没有指定宽度和/或高度。
  • 用户代理尚未支持该图片所用的格式。

属性

此元素支持全局属性

alt
定义了备用的对图像的文本描述。

使用说明: 省略这个属性表明该图像是内容的关键部分,但没有等效的文本可用。把这个属性设置为空字符串,表明该图像不是内容的关键部分,非可视化浏览器在渲染的时候可能会忽略它。

注意:浏览器并非总是会显示图像。比如:

  • 非可视化浏览器(Non-visual browsers)(比如有视力障碍的人使用的音频浏览器)
  • 用户选择不显示图像(比如为了节省带宽,或出于隐私等考虑不加载包括图片在内的第三方资源文件)
  • 图像文件无效,或是使用了不支持的格式

在这些情况下,浏览器很可能会将图像替换为图像所属 <img> 元素的 alt 属性所提供的文本。基于上面罗列的以及更多尚未列出的原因,建议尽可能通过 alt 属性提供一些有用的信息。

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.

将图像复制并粘贴为文本,或是将图像的链接保存到浏览器书签时,也会用到此属性。

crossorigin
这个枚举属性表明是否必须使用 CORS 完成相关图像的抓取。启用 CORS 的图像 可以在 <canvas> 元素中重复使用,而不会被污染(tainted)。允许的值有:
anonymous
执行一个跨域请求(比如,有 Origin HTTP header)。但是没有发送证书(比如,没有 cookie,没有 X.509 证书,没有 HTTP 基本授权认证)。如果服务器没有把证书给到源站(没有设置 Access-Control-Allow-Origin HTTP 头),图像会被污染,而且它的使用会被限制。
use-credentials
一个有证书的跨域请求(比如,有 Origin HTTP header)被发送 (比如,cookie, 一份证书,或者 HTTP 基本验证信息)。如果服务器没有给源站发送证书(通过 Access-Control-Allow-Credentials HTTP header),图像将会被污染,且它的使用会受限制。
当用户并未显式使用本属性时,默认不使用 CORS 发起请求(例如,不会向服务器发送 HTTP 头部信息),可防止其在 <canvas> 中的使用。如果无效,默认当做 anonymous 关键字生效。更多信息,请查看 CORS 属性设置
decoding

为浏览器提供图像解码方式上的提示。允许的值:

sync
同步解码图像,用于与其他内容进行粒子化的展示。

译者注:这里的原文是:

Decode the image synchronously, for atomic presentation with other content.

我也不知道 atomic presentation 这两个词 这样拼在一起 放到这里 是什么意思,查来查去什么都没有。凭感觉可能是“同步展示”。

async
异步解码图像,以减少其他内容的显示延迟。
auto
默认值:不指定解码方式,由浏览器决定哪一种对用户来说是最合适的。
height
图像的高度,在 HTML5 中的单位是 CSS 像素,在 HTML 4 中既可以是像素,也可以是百分比。可以只指定 widthheight 中的一个值,浏览器会根据原始图像进行缩放。
importance
指示下载资源时相对重要性,或者说优先级。允许的值:
auto
不指定优先级。浏览器可以使用自己的算法来为图像选择优先级。
high
此图像在下载时优先级较高
low
此图像在下载时优先级较低
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
这个布尔属性表示图像是否是服务器端 map 的一部分。如果是,那么点击图片的精准坐标将会被发送到服务器。

使用说明:只有在 <img> 元素是一个拥有有效 href 属性的 <a> 元素的后代元素的情况下,这个属性才会被允许使用。

loading
指示浏览器应当如何加载该图像。允许的值:
eager
立即加载图像,不管它是否在可视视口(visible viewport)之外(默认值)。
lazy
延迟加载图像,直到它和视口接近到一个计算得到的距离,由浏览器定义。
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: No Referer header is sent when navigating to an origin without HTTPS. This is the default if no policy is otherwise specified.
  • origin: The Referer header will include the page's origin (scheme, host, and port).
  • origin-when-cross-origin: Navigating to other origins will limit the included referral data to the scheme, host, and port, while navigating from the same origin will include the full path and query string.
  • unsafe-url: The Referer header will always include the origin, path and query string, but not the fragment, password, or username. This is unsafe because it can leak information from TLS-protected resources to insecure origins.
sizes
表示资源大小的、以逗号隔开的一个或多个字符串。每一个资源大小包括:
  1. 一个媒体条件。最后一项一定是被忽略的。
  2. 一个资源尺寸的值。

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.

资源尺寸的值被用来指定图像的预期尺寸。当 srcset 中的资源使用了宽度描述符 w 时,用户代理会使用当前图像大小来选择 srcset 中合适的一个图像 URL。被选中的尺寸影响图像的显示大小(如果没有影响大小的 CSS 样式被应用的话)。如果没有设置 srcset 属性,或者没有属性值,那么 sizes 属性也将不起作用。

src
图像的 URL,这个属性对 <img> 元素来说是必需的。在支持 srcset 的浏览器中,src 被当做拥有一个像素密度的描述符 1x 的候选图像处理,除非一个图像拥有这个像素密度描述符已经被在 srcset 或者 srcset 包含 w 描述符中定义了。
srcset
以逗号分隔的一个或多个字符串列表表明一系列用户代理使用的可能的图像。每一个字符串由以下组成:
  1. 指向图像的 URL
  2. 可选地,再加一个空格之后,附加以下的其一:
    • 一个宽度描述符,这是一个正整数,后面紧跟 'w' 符号。该整数宽度除以sizes属性给出的资源(source)大小来计算得到有效的像素密度,即换算成和x描述符等价的值。
    • 一个像素密度描述符,这是一个正浮点数,后面紧跟 'x' 符号。

如果没有指定源描述符,那它会被指定为默认的 1x

在相同的 srcset 属性中混合使用宽度描述符和像素密度描述符时,会导致该值无效。重复的描述符(比如,两个源在相同的 srcset 两个源都是 2x)也是无效的。

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. See our Responsive images tutorial for an example.

width
图像的宽度,在 HTML5 中单位是 CSS 像素, 在 HTML 4 中可以是像素也可以是百分比。
usemap
与元素相关联的 image map 的部分 URL(以 '#' 开始的部分)。

使用说明: 如果 <img> 元素是 <a><button> 元素的后代元素则不能使用这个属性。

已废弃的属性

align 使用 vertical-align CSS 属性
图像相对于它周围上下文的对齐。使用 float 和/或 vertical-align 这两个 CSS 属性作为代替,而不是这个废弃的属性。允许的值:
top
等价于 vertical-align: topvertical-align: text-top
middle
等价于 vertical-align: -moz-middle-with-baseline
bottom
默认值,等价于 vertical-align: unsetvertical-align: initial
left
等价于 float: left
right
等价于 float: right
border
图像周围的边框宽度。使用 CSS 属性 border 代替此废弃属性。
hspace
插入到图像的左侧和右侧的空白像素的值。使用 CSS 属性 margin 代替此废弃属性。
longdesc
一个指向更详细的图像描述的链接。可能的值是一个 URL 或一个页面上其他元素的 id

备注: 此属性的当前最新的 W3C 版本,HTML 5.2 中被提到,但在 WHATWG 组织的 HTML Living Standard 中依然处于被移除的状态。它的未来尚无定数;authors should use a WAI-ARIA alternative such as aria-describedby or aria-details.

name
元素的名字。使用 id 属性代替此废弃属性。
vspace
插入到图像的上方和下方的空白像素的数组。使用 CSS 属性 margin 代替此废弃属性。

使用 CSS 为 <img> 附加样式

<img> 是一个替换元素。它的 display 属性的默认值是 inline,但是它的默认分辨率是由被嵌入的图片的原始宽高来确定的,使得它就像 inline-block 一样。你可以为 <img> 设置 border/border-radiuspadding/marginwidthheight 等等的 CSS 属性。

<img> 没有基线(baseline),这意味着,当在一个行内格式的上下文(an inline formatting context)中使用 vertical-align: 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).

根据图像文件的类型,图像可能会有一个原始分辨率(intrinsic dimension)或者叫原始宽高。对于一些类型的图像,原始分辨率并不是必要的。比如说,SVG 图像,如果它们的根 <svg> 元素没有 widthheight 属性,SVG 图像就可以没有原始分辨率。

译者注:原始分辨率/原始宽高是图像的固有属性,基本上就是图像本身的分辨率/宽高。只与图像本身有关,与 <img> 元素的属性、显示分辨率等等无关。点阵图像通常有且只有一个随图片宽高变化的原始分辨率,而矢量图像可以没有。不过,编辑矢量图像时,通常可以手动/编辑器自动为其设置原始分辨率。

示例

备用文字

下面的示例将图像嵌入到页面中,且包含用于改善可访问性的备用文本。

<img src="https://developer.mozilla.org/static/img/favicon144.png"
     alt="MDN logo">

图像链接

此示例建立在前一个示例的基础上,展示了如何将图像转换为链接。为做到这一点,将 <img> 标签嵌套在 <a> 之内。这时,备用文本应当描述链接所指向的资源,就像是文本链接一样。

<a href="https://developer.mozilla.org">
  <img src="https://developer.mozilla.org/static/img/favicon144.png"
       alt="Visit the MDN site">
</a>

使用 srcset 属性

在这个例子中,我们包含了一个 srcset 属性,它引用了 MDN 标志高清版本;在高分辨率设备上,它将被优先加载,取代 src 属性中的图像。在支持 srcset用户代理中,src 属性中的图片被作为 1x 候选项。

 <img src="https://developer.mozilla.org/static/img/favicon72.png" 
      alt="MDN logo" 
      srcset="https://developer.mozilla.org/static/img/favicon144.png 2x">

使用 srcsetsizes 属性

在支持 srcset 的用户代理中,当使用 w 描述符时,src 属性会被忽略。当匹配了媒体条件 (min-width: 600px) 时,图像将宽 200px,否则宽 50vw(视图宽度的50%)。

 <img src="/files/16864/clock-demo-200px.png" 
      alt="Clock" 
      srcset="/files/16864/clock-demo-200px.png 200w,
          /files/16797/clock-demo-400px.png 400w"
      sizes="(max-width: 600px) 200px, 50vw">

若要看到大小调整的效果,请打开单独的页面查看示例,以便拖动窗口,调整内容区域的大小。

安全与隐私方面的考量

虽然 <img> 元素的用途是很单纯(原文:innocent)的,但是它们可对用户安全和隐私造成不良的后果。See Referer header: privacy and security concerns for more information and mitigations.

可访问性考量

使用有实际意义的备用描述

alt 属性的值应该清晰、简洁地描述图像的内容。它不应该描述“图像的存在”,或仅仅包含图像的文件名。如果因为图像没有等价的文本描述, alt 属性只得不写或留白,那么可以考虑使用其他方法来呈现图像试图传递的内容。

别这样

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

这样好

<img alt="一只站在沙滩上的跳岩企鹅。" src="penguin.jpg">

当图像上没有 alt 属性时,一些屏幕阅读器可能会读出图像的文件名。如果文件名不能代表图像的内容,甚至是一团乱码,这可只能造成令人迷惑的体验。

title 属性

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.

技术信息

内容类别 流式内容短语内容嵌入内容, palpable content. If the element has a usemap attribute, it also is a part of the interactive content category.
允许的内容 无,它是一个 空元素
标签省略 必须有开始标签,不可有结束标签。
允许的父元素 接受嵌入内容的任意元素。
允许的 ARIA 角色 任意
DOM 接口 HTMLImageElement

规范

规范 状态 说明
Referrer Policy
referrer attribute
Candidate Recommendation Added the referrerpolicy attribute.
HTML Living Standard
<img>
Living Standard
HTML5
<img>
Recommendation
HTML 4.01 Specification
<img>
Recommendation

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
imgChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
align
Deprecated
Chrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
altChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
border
Deprecated
Chrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
crossoriginChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
decodingChrome Full support YesEdge ? Firefox Full support 63IE No support NoOpera Full support YesSafari No support NoWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 63Opera Android Full support YesSafari iOS No support NoSamsung Internet Android Full support Yes
heightChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
hspace
Deprecated
Chrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
intrinsicsize
ExperimentalNon-standard
Chrome Full support 71
Disabled
Full support 71
Disabled
Disabled From version 71: this feature is behind the #enable-experimental-productivity-features preference. To change preferences in Chrome, visit chrome://flags.
Edge ? Firefox ? IE No support NoOpera Full support 58Safari No support NoWebView Android Full support 71
Disabled
Full support 71
Disabled
Disabled From version 71: this feature is behind the #enable-experimental-productivity-features preference.
Chrome Android Full support 71
Disabled
Full support 71
Disabled
Disabled From version 71: this feature is behind the #enable-experimental-productivity-features preference. To change preferences in Chrome, visit chrome://flags.
Firefox Android ? Opera Android Full support 50Safari iOS No support NoSamsung Internet Android Full support 10.0
Disabled
Full support 10.0
Disabled
Disabled From version 10.0: this feature is behind the #enable-experimental-productivity-features preference.
ismapChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
longdescChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
name
Deprecated
Chrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
onerror
Deprecated
Chrome Full support YesEdge ? Firefox Full support 51IE ? Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 51Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
referrerpolicyChrome Full support 51Edge No support NoFirefox Full support 50IE No support NoOpera Full support 38Safari Full support 11.1WebView Android Full support 51Chrome Android Full support 51Firefox Android Full support 50Opera Android Full support 41Safari iOS No support NoSamsung Internet Android Full support 7.2
sizesChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
srcChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
srcsetChrome Full support 34Edge Full support YesFirefox Full support 38
Full support 38
No support 32 — 52
Disabled
Disabled From version 32 until version 52 (exclusive): this feature is behind the dom.image.srcset.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 21Safari Full support 8WebView Android Full support 37Chrome Android Full support 34Firefox Android Full support 38
Full support 38
No support 32 — 52
Disabled
Disabled From version 32 until version 52 (exclusive): this feature is behind the dom.image.srcset.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.
Opera Android Full support 21Safari iOS Full support 8Samsung Internet Android Full support 2.0
usemapChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
vspace
Deprecated
Chrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
widthChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung 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.

另见