<img>:图片嵌入元素
Try it
上面的示例显示了 <img> 元素的用法:
¥The above example shows usage of the <img> element:
src属性是必需的,包含要嵌入的图片的路径。alt属性包含图片的文本替换,这是强制性的,并且对于可访问性非常有用 - 屏幕阅读器向用户读出属性值,以便他们知道图片的含义。如果由于某种原因无法加载图片,替代文本也会显示在页面上:例如,网络错误、内容阻止或链接失效。
还有许多其他属性可以实现各种目的:
¥There are many other attributes to achieve various purposes:
- 推荐人/CORS 安全和隐私控制:参见
crossorigin和referrerpolicy。 - 使用
width和height设置图片的固有大小,允许其在加载之前占用空间,以减轻内容布局的变化。 - 带有
sizes和srcset的响应式图片提示(另请参阅<picture>元素和我们的 响应式图片 教程)。
支持的图片格式
¥Supported image formats
HTML 标准没有列出支持哪些图片格式,因此 user agents 可能支持不同的格式。
¥The HTML standard doesn't list what image formats to support, so user agents may support different formats.
注意:图片文件类型和格式指南 提供有关图片格式及其网络浏览器支持的全面信息。本节只是一个总结!
¥Note: The Image 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:
- APNG(动画可移植网络图形) — 无损动画序列的不错选择(GIF 性能较差)
- AVIF(AV1 图片文件格式) — 由于高性能,对于图片和动画图片来说都是不错的选择。
- GIF(图形交换格式) — 简单图片和动画的不错选择。
- JPEG(联合摄影专家组图片) — 静态图片有损压缩的不错选择(目前最流行)。
- PNG(可移植网络图形) — 静态图片无损压缩的不错选择(质量比 JPEG 稍好)。
- SVG(可缩放矢量图形) — 矢量图片格式。用于必须以不同尺寸精确绘制的图片。
- WebP(网页图片格式) — 图片和动画图片的绝佳选择
建议使用 WebP 和 AVIF 等格式,因为对于静态图片和动画图片来说,它们的性能比 PNG、JPEG、GIF 好得多。
¥Formats like WebP and AVIF are recommended as they perform much better than PNG, JPEG, GIF for both still and animated images.
对于必须以不同尺寸精确绘制的图片,SVG 仍然是推荐的格式。
¥SVG remains the recommended format for images that must be drawn accurately at different sizes.
图片加载错误
¥Image loading errors
如果加载或渲染图片时发生错误,并且已为 error 事件设置了 onerror 事件处理程序,则将调用该事件处理程序。这可能在多种情况下发生,包括:
¥If an error occurs while loading or rendering an image, and an onerror event handler has been set for the error event, that event handler will get called. This can happen in several situations, including:
src属性为空 ("") 或null。srcURL 与用户当前所在页面的 URL 相同。- 图片以某种方式损坏,导致无法加载。
- 图片的元数据已损坏,无法检索其尺寸,并且
<img>元素的属性中未指定尺寸。 - 该图片的格式不受 user agent 支持。
属性
¥Attributes
该元素包括 全局属性。
¥This element includes the global attributes.
alt-
定义可以替换页面中图片的文本。
注意:浏览器并不总是显示图片。在多种情况下,浏览器可能无法显示图片,例如:
¥Note: Browsers do not always display images. There are a number of situations in which a browser might not display images, such as:
- 非视觉浏览器(例如视力障碍人士使用的浏览器)
- 用户选择不显示图片(节省带宽、隐私原因)
- 图片无效或者是 不支持的类型
在这些情况下,浏览器可能会将图片替换为元素的
alt属性中的文本。由于这些原因和其他原因,请尽可能为alt提供有用的值。¥In these cases, the browser may replace the image with the text in the element's
altattribute. For these reasons and others, provide a useful value foraltwhenever possible.将此属性设置为空字符串 (
alt="") 表示此图片不是内容的关键部分(它是装饰或跟踪像素),并且非可视浏览器可能会从 rendering 中忽略它。如果alt属性为空且图片无法显示,视觉浏览器也会隐藏损坏的图片图标。将图片复制并粘贴到文本或将链接图片保存到书签时也会使用此属性。
attributionsrcExperimental-
指定你希望浏览器随图片请求一起发送
Attribution-Reporting-Eligible标头。在服务器端,这用于触发在响应中发送
Attribution-Reporting-Register-Source或Attribution-Reporting-Register-Trigger标头,以分别注册基于图片的 归因来源 或 归因触发器。应该发回哪个响应标头取决于触发注册的Attribution-Reporting-Eligible标头的值。一旦浏览器收到包含图片文件的响应,就会触发相应的源或触发事件。
注意:有关详细信息,请参阅 归因报告 API。
¥Note: See the Attribution Reporting API for more details.
你可以设置此属性的两个版本:
- 布尔值,即仅
attributionsrc名称。这指定你希望将Attribution-Reporting-Eligible标头发送到与src属性指向相同的服务器。当你在同一台服务器上处理归因源或触发器注册时,这样做是可以的。注册归因触发器时,此属性是可选的,如果省略,将使用布尔值。 - 包含一个或多个 URL 的值,例如:
html<img src="image-file.png" alt="My image file description" attributionsrc="https://a.example/register-source https://b.example/register-source" />这在请求的资源不在你控制的服务器上,或者你只想处理在其他服务器上注册归因源的情况下很有用。在这种情况下,你可以指定一个或多个 URL 作为
attributionsrc的值。发生资源请求时,除了资源来源外,Attribution-Reporting-Eligible标头还将发送到attributionSrc中指定的 URL。然后,这些 URL 可以根据需要使用Attribution-Reporting-Register-Source或Attribution-Reporting-Register-Trigger标头进行响应以完成注册。注意:指定多个 URL 意味着可以在同一功能上注册多个归因源。例如,你可能有不同的活动要衡量其成功率,这涉及针对不同的数据生成不同的报告。
¥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-
指示是否必须使用 CORS 请求来获取图片。从 CORS 请求返回的 支持 CORS 的镜像 中的图片数据可以在
<canvas>元素中重用,而无需标记为“tainted”。如果未指定
crossorigin属性,则会发送非 CORS 请求(不带Origin请求标头),浏览器会将图片标记为受污染并限制对其图片数据的访问,从而阻止其在<canvas>元素中使用。如果指定了
crossorigin属性,则发送 CORS 请求(带有Origin请求头);但如果服务器不选择允许源站点对图片数据进行跨源访问(通过不发送任何Access-Control-Allow-Origin响应标头,或者不将站点的源包含在它发送的任何Access-Control-Allow-Origin响应标头中),则浏览器 阻止图片加载,并将 CORS 错误记录到 devtools 控制台。允许值:
anonymous-
发送 CORS 请求时省略凭据(即没有 cookies、X.509 证书 或
Authorization请求标头)。 use-credentials-
CORS 请求与包含的任何凭据(即 cookie、X.509 证书和
Authorization请求标头)一起发送。如果服务器不选择与源站点共享凭据(通过发回Access-Control-Allow-Credentials: true响应标头),则浏览器会将图片标记为受污染并限制对其图片数据的访问。
如果该属性具有无效值,浏览器会像使用
anonymous值一样处理它。请参阅 CORS 设置属性 了解更多信息。 decoding-
此属性向浏览器提供提示,指示浏览器是否应该在看起来更 "correct" (
sync) 的单个呈现步骤中执行图片解码并渲染其他 DOM 内容,或者首先渲染并呈现其他 DOM 内容,然后解码图片 稍后呈现(async)。实际上,async意味着下一次绘制不等待图片解码。在静态
<img>元素上使用decoding时,通常很难察觉到任何明显的效果。它们最初可能会被渲染为空图片,同时获取图片文件(从网络或从缓存),然后独立处理,因此内容更新的 "syncing" 不太明显。然而,解码时发生的渲染阻塞虽然通常很小,但可以测量 - 即使很难用人眼观察到。请参阅 图片解码属性实际上有什么作用? 了解更详细的分析(tunetheweb.com,2023)。通过 JavaScript 将
<img>元素动态插入 DOM 时,使用不同的decoding类型可能会导致更明显的差异 - 有关更多详细信息,请参阅HTMLImageElement.decoding。允许值:
elementtiming-
标记图片以供
PerformanceElementTimingAPI 观察。给定的值成为观察到的图片元素的标识符。另请参见elementtiming属性页。 fetchpriority-
提供获取图片时要使用的相对优先级的提示。允许值:
height-
图片的固有高度(以像素为单位)。必须是没有单位的整数。
注意:包括
height和width可使浏览器在加载图片之前计算图片的 aspect ratio。此纵横比用于保留显示图片所需的空间,减少甚至防止图片下载并绘制到屏幕时的布局变化。减少布局偏移是良好用户体验和 Web 性能的主要组成部分。¥Note: Including
heightandwidthenables the aspect 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-
该布尔属性指示该图片是 服务器端地图 的一部分。如果是这样,用户单击图片的坐标将被发送到服务器。
注意:仅当
<img>元素是具有有效href属性的<a>元素的后代时,才允许使用此属性。这为没有定点设备的用户提供了一个后备目的地。¥Note: This attribute is allowed only if the
<img>element is a descendant of an<a>element with a validhrefattribute. This gives users without pointing devices a fallback destination. loading-
指示浏览器应如何加载图片:
eager-
立即加载图片,无论图片当前是否位于可见视口内(这是默认值)。
lazy-
推迟加载图片,直到图片达到浏览器定义的距视口的计算距离。目的是避免处理图片所需的网络和存储带宽,直到相当确定需要它为止。这通常会提高大多数典型用例中内容的性能。
注意:仅当启用 JavaScript 时才会延迟加载。这是一种反跟踪措施,因为如果用户代理在禁用脚本时支持延迟加载,则站点仍然可以通过策略性地将图片放置在页面的标记中来跟踪用户在整个会话中的大致滚动位置,以便 服务器可以跟踪请求的图片数量和时间。注意:
loading设置为lazy的图片如果不与元素的可见部分相交,则永远不会被加载,即使加载它们会改变这一点,因为卸载的图片具有width和height的0。将width和height放在延迟加载的图片上可以解决此问题,并且是最佳实践,规范推荐的。这样做还有助于防止布局变化。¥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 with
loadingset tolazywill 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 awidthandheightof0. Puttingwidthandheighton lazyloaded images fixes this issue and is a best practice, recommended by the specification. Doing so also helps prevent layout shifts. referrerpolicy-
指示获取资源时使用哪个引用者的字符串:
no-referrer:Referer标头将不会被发送。no-referrer-when-downgrade:如果没有 TLS (HTTPS),Referer标头将不会发送到 origin。origin:发送的引荐来源网址将仅限于引荐页面的来源:它是 scheme、host 和 port。origin-when-cross-origin:发送到其他来源的引用将受到方案、主机和端口的限制。同一原点的导航仍将包含该路径。same-origin:将发送 same origin 的引荐来源网址,但跨源请求将不包含引荐来源网址信息。strict-origin:仅当协议安全级别保持不变 (HTTPS→HTTPS) 时才将文档的来源作为引用站点发送,但不要将其发送到安全性较低的目的地 (HTTPS→HTTP)。strict-origin-when-cross-origin(默认):执行同源请求时发送完整 URL,仅在协议安全级别保持相同时发送源(HTTPS→HTTPS),并且不向安全性较低的目的地发送标头(HTTPS→HTTP)。unsafe-url:引荐来源网址将包括来源和路径(但不包括 fragment、password 或 username)。此值不安全,因为它会将受 TLS 保护的资源的来源和路径泄漏到不安全的来源。
sizes-
一个或多个以逗号分隔的字符串,指示一组源大小。每个源大小包括:
- A 媒体条件.对于列表中的最后一项,必须省略此项。
- 源大小值。
媒体条件描述视口的属性,而不是图片的属性。例如,如果视口不高于 500px,
(max-height: 500px) 1000px建议使用 1000px 宽度的源。源尺寸值指定图片的预期显示尺寸。当使用宽度 (
w) 描述符描述这些源时,User agents 使用当前源大小来选择srcset属性提供的源之一。所选源尺寸会影响图片的 intrinsic size(如果未应用 CSS 样式,则为图片的显示尺寸)。如果srcset属性不存在,或者不包含带有宽度描述符的值,则sizes属性无效。 src-
图片 URL。
<img>元素是必需的。在支持srcset的 browsers 上,src被视为具有像素密度描述符1x的候选图片,除非具有该像素密度描述符的图片已在srcset中定义,或者除非srcset包含w描述符。 srcset-
以逗号分隔的一个或多个字符串,表示 user agent 可能使用的图片源。每个字符串由以下部分组成:
- 图片的 URL
- (可选)空格后跟以下之一:
- 宽度描述符(直接跟随
w的正整数)。宽度描述符除以sizes属性中给出的源尺寸即可计算有效像素密度。 - 像素密度描述符(正浮点数,后面紧跟
x)。
- 宽度描述符(直接跟随
如果未指定描述符,则为源分配默认描述符
1x。在同一个
srcset属性中混合宽度描述符和像素密度描述符是不正确的。重复的描述符(例如,同一srcset中的两个源都用2x描述)也是无效的。如果
srcset属性使用宽度描述符,则sizes属性也必须存在,否则srcset本身将被忽略。用户代理自行选择任何可用的源。这为他们提供了很大的余地,可以根据用户偏好或 bandwidth 条件等因素来定制选择。有关示例,请参阅我们的 响应式图片 教程。
width-
图片的固有宽度(以像素为单位)。必须是没有单位的整数。
usemap-
注意:如果
<img>元素位于<a>或<button>元素内,则无法使用此属性。¥Note: You cannot use this attribute if the
<img>element is inside an<a>or<button>element.
已弃用的属性
¥Deprecated attributes
alignDeprecated-
将图片与其周围环境对齐。使用
float和/或vertical-alignCSS 属性代替此属性。允许值: borderDeprecatedhspaceDeprecated-
图片左侧和右侧空白的像素数。请改用
marginCSS 属性。 longdescDeprecated-
指向图片更详细描述的链接。可能的值为 URL 或元素
id。注意:该属性在最新的 W3C 版本 HTML 5.2 中提到,但已从 WHATWG 的 HTML 生活标准 中删除。它的未来是不确定的;作者应该使用 WAI-ARIA 替代方案,例如
aria-describedby或aria-details。¥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-describedbyoraria-details. nameDeprecated-
元素的名称。请改用
id属性。 vspaceDeprecated-
图片上方和下方空白区域的像素数。请改用
marginCSS 属性。
使用 CSS 设计样式
¥Styling with CSS
<img> 是 被替换的元素;默认情况下,它的 display 值为 inline,但其默认尺寸由嵌入图片的内在值定义,就像 inline-block 一样。你可以在图片上设置 border/border-radius、padding/margin、width、height 等属性。
¥<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> 没有基线,因此当图片在 vertical-align: baseline 的内联格式化上下文中使用时,图片的底部将放置在文本基线上。
¥<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.
你可以使用 object-position 属性在元素的框中定位图片,并使用 object-fit 属性调整框中图片的大小(例如,图片是否应该适合框或填充它,即使需要剪切)。
¥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).
根据其类型,图片可能具有固有的宽度和高度。然而,对于某些图片类型,固有尺寸是不必要的。例如,如果 SVG 图片的根 <svg> 元素没有设置 width 或 height,则 SVG 图片没有固有尺寸。
¥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.
无障碍
创作有意义的替代描述
¥Authoring meaningful alternate descriptions
alt 属性的值应该为图片内容提供清晰简洁的文本替换。它不应描述图片本身的存在或图片的文件名。如果由于图片没有等效文本而故意省略 alt 属性,请考虑使用替代方法来呈现图片试图传达的内容。
¥An alt 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 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" />
做
¥Do
<img alt="A Rockhopper Penguin is standing on a beach." src="penguin.jpg" />
当图片上不存在 alt 属性时,某些屏幕阅读器可能会读出图片的文件名。如果文件名不能代表图片的内容,这可能会是一种令人困惑的体验。
¥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.
将 SVG 识别为图片
¥Identifying SVG as an image
由于 旁白错误,VoiceOver 无法正确地将 SVG 图片朗读为图片。将 role="img" 包含到 SVG 源文件的所有 <img> 元素中,以确保辅助技术正确地将 SVG 声明为图片内容。
¥Due to a VoiceOver bug, VoiceOver does not correctly announce SVG images as images. Include role="img" to all <img> elements with SVG source files to ensure assistive technologies correctly announce the SVG as image content.
<img src="mdn.svg" alt="MDN" role="img" />
标题属性
¥The title attribute
title 属性不能替代 alt 属性。此外,请避免在同一图片上声明的 title 属性中重复 alt 属性的值。这样做可能会导致某些屏幕阅读器两次读出相同的文本,从而造成令人困惑的体验。
¥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 same text twice, creating a confusing experience.
title 属性也不应该用作伴随图片的 alt 描述的补充字幕信息。如果图片需要标题,请使用 figure 和 figcaption 元素。
¥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.
title 属性的值通常作为工具提示呈现给用户,在光标停止在图片上移动后不久就会出现。虽然这可以向用户提供附加信息,但你不应假设用户会看到它:用户可能只有键盘或触摸屏。如果你有对用户特别重要或有价值的信息,请使用上述方法之一内联呈现,而不是使用 title。
¥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.
示例
替代文本
图片链接
¥Image link
此示例建立在前一个示例的基础上,展示如何将图片转换为链接。为此,请将 <img> 标签嵌套在 <a> 内。你应该使用替代文本来描述链接指向的资源,就像你使用文本链接一样。
¥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.
<a href="https://web.nodejs.cn">
<img src="favicon144.png" alt="Visit the MDN site" />
</a>
使用 srcset 属性
¥Using the srcset attribute
在此示例中,我们包含一个 srcset 属性,该属性引用了徽标的高分辨率版本;这将代替高分辨率设备上的 src 图片进行加载。src 属性中引用的图片被计为支持 srcset 的 user agents 中的 1x 候选。
¥In this example we include a srcset attribute with 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="favicon72.png" alt="MDN" srcset="favicon144.png 2x" />
使用 srcset 和 size 属性
¥Using the srcset and sizes attributes
当包含 w 描述符时,在支持 srcset 的 user agents 中,src 属性将被忽略。当 (max-width: 600px) 媒体条件匹配时,将加载 200 像素宽的图片(它是与 200px 最匹配的图片),否则将加载另一张图片。
¥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 200 pixel-wide image will load (it is the one that matches 200px most closely), otherwise the other image will load.
<img
src="clock-demo-200px.png"
alt="The time is 12:45."
srcset="clock-demo-200px.png 200w, clock-demo-400px.png 400w"
sizes="(max-width: 600px) 200px, 50vw" />
注意:要查看实际的大小调整,view the example on a separate page,以便你可以实际调整内容区域的大小。
¥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
尽管 <img> 元素具有无害用途,但它们可能会对用户安全和隐私产生不良后果。请参阅 引用头:隐私和安全问题 了解更多信息和缓解措施。
¥Although <img> elements have innocent uses, they can have undesirable consequences for user security and privacy. See Referer header: privacy and security concerns for more information and mitigations.
技术总结
¥Technical summary
| 内容类别 |
流量内容,
措辞内容,
嵌入内容,
可触知的内容.如果该元素具有 usemap 属性,那么它也是交互式内容类别的一部分。
|
|---|---|
| 允许的内容 | 没有任何;这是 void element。 |
| 标签遗漏 | 必须有开始标记,并且不能有结束标记。 |
| 允许的父级 | 任何接受嵌入内容的元素。 |
| 隐式 ARIA 角色 |
|
| 允许的 ARIA 角色 |
|
| DOM 接口 | HTMLImageElement |
规范
| Specification |
|---|
| HTML Standard # the-img-element |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also
<picture>、<object>和<embed>元素object-fit、object-position、image-orientation、image-rendering和image-resolution:与图片相关的 CSS 属性。- 该元素的
HTMLImageElement接口 - HTML 中的图片
- 图片文件类型和格式指南
- 响应式图片