1. 4.8.4 图片
        1. 4.8.4.1 概述
          1. 4.8.4.1.1 自适应图片
        2. 4.8.4.2 Attributes common to source, img, and link elements
          1. 4.8.4.2.1 Srcset attributes
          2. 4.8.4.2.2 Sizes attributes
        3. 4.8.4.3 Processing model
          1. 4.8.4.3.1 When to obtain images
          2. 4.8.4.3.2 响应 DOM 变化
          3. 4.8.4.3.3 The list of available images
          4. 4.8.4.3.4 Decoding images
          5. 4.8.4.3.5 Updating the image data
          6. 4.8.4.3.6 Selecting an image source
          7. 4.8.4.3.7 Updating the source set
          8. 4.8.4.3.8 Parsing a srcset attribute
          9. 4.8.4.3.9 Parsing a sizes attribute
          10. 4.8.4.3.10 源像素密度规范化
          11. 4.8.4.3.11 Reacting to environment changes
        4. 4.8.4.4 为图片提供替代文字的要求
          1. 4.8.4.4.1 通用指引
          2. 4.8.4.4.2 只包含图片的链接或按钮
          3. 4.8.4.4.3 A phrase or paragraph with an alternative graphical representation: charts, diagrams, graphs, maps, illustrations
          4. 4.8.4.4.4 带有替代图形表示的短语或标签:图标,徽标
          5. 4.8.4.4.5 Text that has been rendered to a graphic for typographical effect
          6. 4.8.4.4.6 A graphical representation of some of the surrounding text
          7. 4.8.4.4.7 辅助性图片
          8. 4.8.4.4.8 不提供任何信息的纯装饰性图片
          9. 4.8.4.4.9 组成但个没有链接的大图的图片组
          10. 4.8.4.4.10 组成单个有链接的大图的图片组
          11. 4.8.4.4.11 内容的关键部分
          12. 4.8.4.4.12 不是给用户看的图片
          13. 4.8.4.4.13 An image in an email or private document intended for a specific person who is known to be able to view images
          14. 4.8.4.4.14 Guidance for markup generators
          15. 4.8.4.4.15 规范检查工具指引

4.8.4 图片

4.8.4.1 概述

This section is non-normative.

在 HTML 中嵌入图片时,如果只有一个图片资源,就使用 img 元素和它的 src 属性。

<h2>From today's featured article</h2>
<img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

但是有些情况下作者希望提供多张图片让用户代理选择:

上述各种情形不是互斥的。例如,结合不同的 设备像素比 和不同的 美术设计 来提供不同的资源也是合理的。

虽然可以使用脚本来解决这些问题,但这样会引起一些其他问题:

考虑到这些,本规范引入了一些功能,以声明的方式解决上述问题。

当图片的渲染大小固定的情况下,基于 设备像素比 选择

img 元素上可以使用 srcsrcset 属性, 使用 x 描述符来提供多个只有大小不同的图片(小图是大图的缩略版)。

当图片的渲染大小依赖于 viewport 宽度时 (基于视口的选择), 使用 x 描述符不合适, 但该描述符可以与 美术设计 一起使用。

<h2>From today's featured article</h2>
<img src="/uploads/100-marie-lloyd.jpg"
     srcset="/uploads/150-marie-lloyd.jpg 1.5x, /uploads/200-marie-lloyd.jpg 2x"
     alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

用户代理可以根据用户屏幕像素密度、缩放级别,以及可能的其他因素比如用户的网络条件选择任何一个给出的资源。

为了向后兼容其他老的不知道 srcset 属性的用户代理 , 其中一个 URL 在 img 元素的 src 属性上也有指定。 这样即使在老的用户代理中也能显示一些有用的(虽然可能比用户预期的分辨率低)东西。 对于新的用户代理,src 属性也会参与资源选择,就像它被写在 srcset 中并有一个 1x 描述符一样。

图片的渲染大小由 widthheight 属性给出,使得用户代理可以在它下载完之前分配空间。

基于视口的选择

可以使用 srcsetsizes 属性,使用 w 描述符来提供多个只有大小不同的图片 (小图是大图的缩略版)。

在这个例子中,有一个横幅(使用适当的 CSS)横跨整个 视口 宽度。

<h1><img sizes="100vw" srcset="wolf-400.jpg 400w, wolf-800.jpg 800w, wolf-1600.jpg 1600w"
     src="wolf-400.jpg" alt="The rad wolf"></h1>

用户代理将会根据指定的 w 描述符和 sizes 属性指定的渲染大小为每个图片计算等效像素密度。 然后它可以根据用户屏幕的像素密度、缩放级别和任何可能的其他因素(比如用户网络状态)选择任何一个资源。

如果用户屏幕是 320 CSS 像素 宽,这等价于指定 wolf-400.jpg 1.25x, wolf-800.jpg 2.5x, wolf-1600.jpg 5x。 另一方面,如果用户屏幕是 1200 CSS 像素 宽,这等价于指定 wolf-400.jpg 0.33x, wolf-800.jpg 0.67x, wolf-1600.jpg 1.33x.。 通过使用 w 描述符和 sizes 属性, 不论用户设备有多大用户代理都可以选择下载正确的图片资源。

为了向后兼容,其中一个 URL 也指定在 img 元素的 src 属性上。在新的用户代理中,当 srcset 属性使用 w 描述符时, src 属性会被忽略。

在这个例子中,网页基于 视口 宽度有三个布局。 窄的布局有一列图片(每个图片宽度大约是 100%), 中等布局有两列图片(每个图片宽度大约是 50%), 最宽的布局有三列图片和一些页面边距(每个图片大约是 33%)。 在 视口 宽度为 30em50em 时会切换布局。

<img sizes="(max-width: 30em) 100vw, (max-width: 50em) 50vw, calc(33vw - 100px)"
     srcset="swing-200.jpg 200w, swing-400.jpg 400w, swing-800.jpg 800w, swing-1600.jpg 1600w"
     src="swing-400.jpg" alt="Kettlebell Swing">

sizes 属性设置了布局的切换点为 30em50em,也声明了在这些切换点之间图片大小为 100vw, 50vw, 或 calc(33vw - 100px)。 这些大小不一定要精确匹配 CSS 中指定的真正的图片宽度。

用户代理会从 sizes 属性中选一个宽度, 使用第一个 <media-condition> (括号中的部分)结果为真的大小, 如果所有结果都为假就使用最后一项(calc(33vw - 100px))。

例如,如果 视口 宽度为 29em,那么 (max-width: 30em) 计算为真,就会使用 100vw, 所以资源选择后的图片大小就是 29em。如果 视口 宽度是 32em,那么 (max-width: 30em) 计算为假,但 (max-width: 50em) 计算为真,就会使用 50vw,所以资源选择后图片大小就是 16em(半个 视口 宽度)。 注意更宽一点的 视口 因为布局不同而导致图片更小。

用户代理可以计算等效像素密度并选择合适的资源,类似上一个例子那样。

美术设计

可以使用 picture 元素和 source 元素和 media 属性提供多张内容不同的图片 (例如小的图片是大图的裁剪版)。

<picture>
  <source media="(min-width: 45em)" srcset="large.jpg">
  <source media="(min-width: 32em)" srcset="med.jpg">
  <img src="small.jpg" alt="The wolf runs through the snow.">
</picture>

用户代理会选择 media 属性中的媒体查询匹配的第一个 source 元素,然后从它的 srcset 属性中选择一个合适的 URL。

图片的渲染大小取决于选择了哪张图片。可以使用 CSS 来指定用户代理下载图片之前使用的宽高。

img { width: 300px; height: 300px }
@media (min-width: 32em) { img { width: 500px; height:300px } }
@media (min-width: 45em) { img { width: 700px; height:400px } }

这个例子结合了 美术设计 和 基于 设备像素比 的选择。 这个占半个 视口 的横幅提供了两个版本,一个用于宽屏一个用于窄屏。

<h1>
 <picture>
  <source media="(max-width: 500px)" srcset="banner-phone.jpeg, banner-phone-HD.jpeg 2x">
  <img src="banner.jpeg" srcset="banner-HD.jpeg 2x" alt="The Breakfast Combo">
 </picture>
</h1>
基于图片格式的选择

可以使用 source 元素上的 type 属性来提供多种格式的图片。

<h2>From today's featured article</h2>
<picture>
 <source srcset="/uploads/100-marie-lloyd.webp" type="image/webp">
 <source srcset="/uploads/100-marie-lloyd.jxr" type="image/vnd.ms-photo">
 <img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
</picture>
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

在这个例子中,用户代理会选择第一个 type 属性为支持的 MIME 类型的源。 如果用户代理支持 WebP 就会选择第一个 source 元素。 如果不支持 WebP,但支持 JPEG XR 就会选择第二个 source 元素。 如果这两种都不支持,就会选择 img 元素。

4.8.4.1.1 自适应图片

This section is non-normative.

可以使用 CSS 和媒体查询来构造动态适应用户环境的页面布局, 特别是对不同的 视口 宽高和像素密度。 但 CSS 无法操作内容;这时可以使用 img 元素的 srcset 属性和 picture 元素。 本节将介绍一个示例案例,演示如何使用这些功能。

考虑一个场景,在宽屏(宽于 600 CSS 像素)上要使用一个 300×150 的图片 a-rectangle.png, 但在小一点的屏幕上(不大于 600 CSS 像素)要使用一个 100×100 的图片 a-square.png。这样的标记可能像这样:

<figure>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" alt="Barney Frank wears a suit and glasses.">
 </picture>
 <figcaption>Barney Frank, 2011</figcaption>
</figure>

alt 属性中放什么内容,参考 图片替代文本的要求 一节。

问题在于用户代理在图片加载时不知道使用什么样的宽高。 为了避免页面加载中布局被重排很多次,可以使用 CSS 和 CSS 媒体查询来提供宽高:

<style>
 #a { width: 300px; height: 150px; }
 @media (max-width: 600px) { #a { width: 100px; height: 100px; } }
</style>
<figure>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" alt="Barney Frank wears a suit and glasses." id="a">
 </picture>
 <figcaption>Barney Frank, 2011</figcaption>
</figure>

也可以使用 widthheight 使用来为提供旧的用户代理提供宽高, CSS 只用于支持 picture 的用户代理:

<style media="(max-width: 600px)">
 #a { width: 100px; height: 100px; }
</style>
<figure>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" width="300" height="150"
  alt="Barney Frank wears a suit and glasses." id="a">
 </picture>
 <figcaption>Barney Frank, 2011</figcaption>
</figure>

img 元素指定了 src 属性, 它为不支持 picture 的旧的用户代理给出了图片的 URL。 这就要讨论 src 属性应该提供哪个图片的问题了。

如果作者在旧的用户代理中想要最大的图片,标记可以这样写:

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <img src="pear-desktop.jpeg" alt="The pear is juicy.">
</picture>

但如果旧的用户代理更重要,就可以把所有三个图片都列在 source 元素中,完全重写掉 src 属性。

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <source srcset="pear-desktop.jpeg">
 <img src="pear-mobile.jpeg" alt="The pear is juicy.">
</picture>

因为在这里 src 属性在支持 picture 的用户代理下会被完全忽略,src 属性可以默认写成任何图片, 包括既不是最大的也不是最小的那个:

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <source srcset="pear-desktop.jpeg">
 <img src="pear-tablet.jpeg" alt="The pear is juicy.">
</picture>

上面用到了 max-width 媒体特性,给出了该图片适用的最大 (视口)大小。也可以使用 min-width

<picture>
 <source srcset="pear-desktop.jpeg" media="(min-width: 1281px)">
 <source srcset="pear-tablet.jpeg" media="(min-width: 721px)">
 <img src="pear-mobile.jpeg" alt="The pear is juicy.">
</picture>
4.8.4.2 Attributes common to source, img, and link elements
4.8.4.2.1 Srcset attributes

A srcset attribute is an attribute with requirements defined in this section.

If present, its value must consist of one or more image candidate strings, each separated from the next by a U+002C COMMA character (,). If an image candidate string contains no descriptors and no ASCII whitespace after the URL, the following image candidate string, if there is one, must begin with one or more ASCII whitespace.

An image candidate string consists of the following components, in order, with the further restrictions described below this list:

  1. Zero or more ASCII whitespace.

  2. A valid non-empty URL that does not start or end with a U+002C COMMA character (,), referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted.

  3. Zero or more ASCII whitespace.

  4. Zero or one of the following:

  5. Zero or more ASCII whitespace.

There must not be an image candidate string for an element that has the same width descriptor value as another image candidate string's width descriptor value for the same element.

There must not be an image candidate string for an element that has the same pixel density descriptor value as another image candidate string's pixel density descriptor value for the same element. For the purpose of this requirement, an image candidate string with no descriptors is equivalent to an image candidate string with a 1x descriptor.

If an image candidate string for an element has the width descriptor specified, all other image candidate strings for that element must also have the width descriptor specified.

The specified width in an image candidate string's width descriptor must match the intrinsic width in the resource given by the image candidate string's URL, if it has an intrinsic width.

If an element has a sizes attribute present, all image candidate strings for that element must have the width descriptor specified.

4.8.4.2.2 Sizes attributes

A sizes attribute is an attribute with requirements defined in this section.

If present, the value must be a valid source size list.

A valid source size list is a string that matches the following grammar: [CSSVALUES] [MQ]

<source-size-list> = [ <source-size># , ]? <source-size-value>
<source-size> = <media-condition> <source-size-value>
<source-size-value> = <length>

A <source-size-value> must not be negative, and must not use CSS functions other than the math functions.

The <source-size-value> gives the intended layout width of the image. The author can specify different widths for different environments with <media-condition>s.

Percentages are not allowed in a <source-size-value>, to avoid confusion about what it would be relative to. The 'vw' unit can be used for sizes relative to the viewport width.

4.8.4.3 Processing model

An img element has a current request and a pending request. The current request is initially set to a new image request. The pending request is initially set to null.

An image request has a state, current URL, and image data.

An image request's state is one of the following:

Unavailable
The user agent hasn't obtained any image data, or has obtained some or all of the image data but hasn't yet decoded enough of the image to get the image dimensions.
Partially available
The user agent has obtained some of the image data and at least the image dimensions are available.
Completely available
The user agent has obtained all of the image data and at least the image dimensions are available.
Broken
The user agent has obtained all of the image data that it can, but it cannot even decode the image enough to get the image dimensions (e.g. the image is corrupted, or the format is not supported, or no data could be obtained).

An image request's current URL is initially the empty string.

An image request's image data is the decoded image data.

When an image request's state is either partially available or completely available, the image request is said to be available.

When an img element's current request's state is completely available and the user agent can decode the media data without errors, then the img element is said to be fully decodable.

An image request's state is initially unavailable.

When an img element's current request is available, the img element provides a paint source whose width is the image's density-corrected intrinsic width (if any), whose height is the image's density-corrected intrinsic height (if any), and whose appearance is the intrinsic appearance of the image.


An img element is said to use srcset or picture if it has a srcset attribute specified or if it has a parent that is a picture element.


Each img element has a last selected source, which must initially be null.

Each image request has a current pixel density, which must initially be undefined.

When an img element has a current pixel density that is not 1.0, the element's image data must be treated as if its resolution, in device pixels per CSS pixels, was the current pixel density. The image's density-corrected intrinsic width and height are the intrinsic width and height after taking into account the current pixel density.

For example, if the current pixel density is 3.125, that means that there are 300 device pixels per CSS inch, and thus if the image data is 300x600, it has intrinsic dimensions of 96 CSS pixels by 192 CSS pixels.

All img and link elements are associated with a source set.

A source set is an ordered set of zero or more image sources and a source size.

An image source is a URL, and optionally either a pixel density descriptor, or a width descriptor.

A source size is a <source-size-value>. When a source size has a unit relative to the viewport, it must be interpreted relative to the img element's node document's viewport. Other units must be interpreted the same as in Media Queries. [MQ]


A parse error for algorithms in this section indicates a non-fatal mismatch between input and requirements. User agents are encouraged to expose parse errors somehow.


Whether the image is fetched successfully or not (e.g. whether the response status was an ok status) must be ignored when determining the image's type and whether it is a valid image.

This allows servers to return images with error responses, and have them displayed.

The user agent should apply the image sniffing rules to determine the type of the image, with the image's associated Content-Type headers giving the official type. If these rules are not applied, then the type of the image must be the type given by the image's associated Content-Type headers.

User agents must not support non-image resources with the img element (e.g. XML files whose document element is an HTML element). User agents must not run executable code (e.g. scripts) embedded in the image resource. User agents must only display the first page of a multipage resource (e.g. a PDF file). User agents must not allow the resource to act in an interactive fashion, but should honour any animation in the resource.

This specification does not specify which image types are to be supported.

4.8.4.3.1 When to obtain images

By default, images are obtained immediately. User agents may provide users with the option to instead obtain them on-demand. (The on-demand option might be used by bandwidth-constrained users, for example.)

When obtaining images immediately, the user agent must synchronously update the image data of the img element, with the restart animation flag set if so stated, whenever that element is created or has experienced relevant mutations.

When obtaining images on demand, the user agent must update the image data of an img element whenever it needs the image data (i.e., on demand), but only if the img element's current request's state is unavailable. When an img element has experienced relevant mutations, if the user agent only obtains images on demand, the img element's current request's state must return to unavailable.

4.8.4.3.2 响应 DOM 变化

img 元素 相关的变化 包括:

4.8.4.3.3 The list of available images

Each Document object must have a list of available images. Each image in this list is identified by a tuple consisting of an absolute URL, a CORS settings attribute mode, and, if the mode is not No CORS, an origin. Each image furthermore has an ignore higher-layer caching flag. User agents may copy entries from one Document object's list of available images to another at any time (e.g. when the Document is created, user agents can add to it all the images that are loaded in other Documents), but must not change the keys of entries copied in this way when doing so, and must unset the ignore higher-layer caching flag for the copied entry. User agents may also remove images from such lists at any time (e.g. to save memory). User agents must remove entries in the list of available images as appropriate given higher-layer caching semantics for the resource (e.g. the HTTP `Cache-Control` response header) when the ignore higher-layer caching flag is unset.

The list of available images is intended to enable synchronous switching when changing the src attribute to a URL that has previously been loaded, and to avoid re-downloading images in the same document even when they don't allow caching per HTTP. It is not used to avoid re-downloading the same image while the previous image is still loading.

The user agent can also store the image data separately from the list of available images.

For example, if a resource has the HTTP response header `Cache-Control: must-revalidate`, and its ignore higher-layer caching flag is unset, the user agent would remove it from the list of available images but could keep the image data separately, and use that if the server responds with a 304 Not Modified status.

4.8.4.3.4 Decoding images

Image data is usually encoded in order to reduce file size. This means that in order for the user agent to present the image to the screen, the data needs to be decoded. Decoding is the process which converts an image's media data into a bitmap form, suitable for presentation to the screen. Note that this process can be slow relative to other processes involved in presenting content. Thus, the user agent can choose when to perform decoding, in order to create the best user experience.

Image decoding is said to be synchronous if it prevents presentation of other content until it is finished. Typically, this has an effect of atomically presenting the image and any other content at the same time. However, this presentation is delayed by the amount of time it takes to perform the decode.

Image decoding is said to be asynchronous if it does not prevent presentation of other content. This has an effect of presenting non-image content faster. However, the image content is missing on screen until the decode finishes. Once the decode is finished, the screen is updated with the image.

In both synchronous and asynchronous decoding modes, the final content is presented to screen after the same amount of time has elapsed. The main difference is whether the user agent presents non-image content ahead of presenting the final content.

In order to aid the user agent in deciding whether to perform synchronous or asynchronous decode, the decoding attribute can be set on img elements. The possible values of the decoding attribute are the following image decoding hint keywords:

Keyword State Description
sync Sync Indicates a preference to decode this image synchronously for atomic presentation with other content.
async Async Indicates a preference to decode this image asynchronously to avoid delaying presentation of other content.
auto Auto Indicates no preference in decoding mode (the default).

When decoding an image, the user agent should respect the preference indicated by the decoding attribute's state. If the state indicated is auto, then the user agent is free to choose any decoding behavior.

It is also possible to control the decoding behavior using the decode() method. Since the decode() method performs decoding independently from the process responsible for presenting content to screen, it is unaffected by the decoding attribute.

4.8.4.3.5 Updating the image data

This algorithm cannot be called from steps running in parallel. If a user agent needs to call this algorithm from steps running in parallel, it needs to queue a task to do so.

When the user agent is to update the image data of an img element, optionally with the restart animations flag set, it must run the following steps:

  1. If the element's node document is not the active document, then:

    1. Continue running this algorithm in parallel.

    2. Wait until the element's node document is the active document.

    3. If another instance of this algorithm for this img element was started after this instance (even if it aborted and is no longer running), then return.

    4. Queue a microtask to continue this algorithm.

  2. If the user agent cannot support images, or its support for images has been disabled, then abort the image request for the current request and the pending request, set current request's state to unavailable, set pending request to null, and return.

  3. Let selected source be null and selected pixel density be undefined.

  4. If the element does not use srcset or picture and it has a src attribute specified whose value is not the empty string, then set selected source to the value of the element's src attribute and set selected pixel density to 1.0.

  5. Set the element's last selected source to selected source.

  6. If selected source is not null, then:

    1. Parse selected source, relative to the element's node document. If that is not successful, then abort this inner set of steps. Otherwise, let urlString be the resulting URL string.

    2. Let key be a tuple consisting of urlString, the img element's crossorigin attribute's mode, and, if that mode is not No CORS, the node document's origin.

    3. If the list of available images contains an entry for key, then:

      1. Set the ignore higher-layer caching flag for that entry.

      2. Abort the image request for the current request and the pending request.

      3. Set pending request to null.

      4. Let current request be a new image request whose image data is that of the entry and whose state is completely available.

      5. Update the presentation of the image appropriately.

      6. Set current request's current pixel density to selected pixel density.

      7. Queue an element task on the DOM manipulation task source given the img element and following steps:

        1. If restart animation is set, then restart the animation.

        2. Set current request's current URL to urlString.

        3. Fire an event named load at the img element.

      8. Abort the update the image data algorithm.

  7. Queue a microtask to perform the rest of this algorithm, allowing the task that invoked this algorithm to continue.

  8. If another instance of this algorithm for this img element was started after this instance (even if it aborted and is no longer running), then return.

    Only the last instance takes effect, to avoid multiple requests when, for example, the src, srcset, and crossorigin attributes are all set in succession.

  9. Let selected source and selected pixel density be the URL and pixel density that results from selecting an image source, respectively.

  10. If selected source is null, then:

    1. Set the current request's state to broken, abort the image request for the current request and the pending request, and set pending request to null.

    2. Queue an element task on the DOM manipulation task source given the img element and the following steps:

      1. Change the current request's current URL to the empty string.

      2. If the element has a src attribute or it uses srcset or picture, fire an event named error at the img element.

    3. Return.

  11. Parse selected source, relative to the element's node document, and let urlString be the resulting URL string. If that is not successful, then:

    1. Abort the image request for the current request and the pending request.

    2. Set the current request's state to broken.

    3. Set pending request to null.

    4. Queue an element task on the DOM manipulation task source given the img element and the following steps:

      1. Change the current request's current URL to selected source.

      2. Fire an event named error at the img element.

    5. Return.

  12. If the pending request is not null and urlString is the same as the pending request's current URL, then return.

  13. If urlString is the same as the current request's current URL and current request's state is partially available, then abort the image request for the pending request, queue an element task on the DOM manipulation task source given the img element to restart the animation if restart animation is set, and return.

  14. If the pending request is not null, then abort the image request for the pending request.

  15. Set image request to a new image request whose current URL is urlString.

  16. If current request's state is unavailable or broken, then set the current request to image request. Otherwise, set the pending request to image request.

  17. Let request be the result of creating a potential-CORS request given urlString, "image", and the current state of the element's crossorigin content attribute.

  18. Set request's client to the element's node document's relevant settings object.

  19. If the element uses srcset or picture, set request's initiator to "imageset".

  20. Set request's referrer policy to the current state of the element's referrerpolicy attribute.

  21. Let delay load event be true if the img's lazy loading attribute is in the Eager state, or if scripting is disabled for the img, and false otherwise.

  22. If the will lazy load element steps given the img return true, then:

    1. Set the img's lazy load resumption steps to the rest of this algorithm starting with the step labeled fetch the image.

    2. Start intersection-observing a lazy loading element for the img element.

    3. Return.

  23. Fetch the image: Fetch request. Let this instance of the fetching algorithm be associated with image request.

    The resource obtained in this fashion, if any, is image request's image data. It can be either CORS-same-origin or CORS-cross-origin; this affects the origin of the image itself (e.g. when used on a canvas).

    When delay load event is true, fetching the image must delay the load event of the element's node document until the task that is queued by the networking task source once the resource has been fetched (defined below) has been run.

    This, unfortunately, can be used to perform a rudimentary port scan of the user's local network (especially in conjunction with scripting, though scripting isn't actually necessary to carry out such an attack). User agents may implement cross-origin access control policies that are stricter than those described above to mitigate this attack, but unfortunately such policies are typically not compatible with existing web content.

  24. Continue the remaining steps in parallel, but without missing any data from fetching.

  25. As soon as possible, jump to the first applicable entry from the following list:

    If the resource type is multipart/x-mixed-replace

    The next task that is queued by the networking task source while the image is being fetched must run the following steps:

    1. If image request is the pending request and at least one body part has been completely decoded, abort the image request for the current request, upgrade the pending request to the current request.

    2. Otherwise, if image request is the pending request and the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, abort the image request for the current request, upgrade the pending request to the current request, and set the current request's state to broken.

    3. Otherwise, if image request is the current request, its state is unavailable, and the user agent is able to determine image request's image's width and height, set the current request's state to partially available.

    4. Otherwise, if image request is the current request, its state is unavailable, and the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, set the current request's state to broken.

    Each task that is queued by the networking task source while the image is being fetched must update the presentation of the image, but as each new body part comes in, it must replace the previous image. Once one body part has been completely decoded, the user agent must set the img element's current request's state to completely available and queue an element task on the DOM manipulation task source given the img element to fire an event named load at the img element.

    If the resource type and data corresponds to a supported image format, as described below

    The next task that is queued by the networking task source while the image is being fetched must run the following steps:

    1. If the user agent is able to determine image request's image's width and height, and image request is pending request, set image request's state to partially available.

    2. Otherwise, if the user agent is able to determine image request's image's width and height, and image request is current request, update the img element's presentation appropriately and set image request's state to partially available.

    3. Otherwise, if the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, and image request is pending request, abort the image request for the current request and the pending request, upgrade the pending request to the current request, set current request's state to broken, and fire an event named error at the img element.

    4. Otherwise, if the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, and image request is current request, abort the image request for image request and fire an event named error at the img element.

    That task, and each subsequent task, that is queued by the networking task source while the image is being fetched, if image request is the current request, must update the presentation of the image appropriately (e.g., if the image is a progressive JPEG, each packet can improve the resolution of the image).

    Furthermore, the last task that is queued by the networking task source once the resource has been fetched must additionally run these steps:

    1. If image request is the pending request, abort the image request for the current request, upgrade the pending request to the current request and update the img element's presentation appropriately.

    2. Set image request to the completely available state.

    3. Add the image to the list of available images using the key key, with the ignore higher-layer caching flag set.

    4. Fire an event named load at the img element.

    Otherwise

    The image data is not in a supported file format; the user agent must set image request's state to broken, abort the image request for the current request and the pending request, upgrade the pending request to the current request if image request is the pending request, and then queue an element task on the DOM manipulation task source given the img element to fire an event named error at the img element.

While a user agent is running the above algorithm for an element x, there must be a strong reference from the element's node document to the element x, even if that element is not connected.

To abort the image request for an image request image request means to run the following steps:

  1. Forget image request's image data, if any.

  2. Abort any instance of the fetching algorithm for image request, discarding any pending tasks generated by that algorithm.

To upgrade the pending request to the current request for an img element means to run the following steps:

  1. Let the img element's current request be the pending request.

  2. Let the img element's pending request be null.

4.8.4.3.6 Selecting an image source

When asked to select an image source for a given img or link element el, user agents must do the following:

  1. Update the source set for el.

  2. If el's source set is empty, return null as the URL and undefined as the pixel density.

  3. Otherwise, take el's source set and let it be source set.

  4. If an entry b in source set has the same associated pixel density descriptor as an earlier entry a in source set, then remove entry b. Repeat this step until none of the entries in source set have the same associated pixel density descriptor as an earlier entry.

  5. In a user agent-specific manner, choose one image source from source set. Let this be selected source.

  6. Return selected source and its associated pixel density.

4.8.4.3.7 Updating the source set

When asked to update the source set for a given img or link element el, user agents must do the following:

  1. Set el's source set to an empty source set.

  2. Let elements be « el ».

  3. If el is an img element whose parent node is a picture element, then replace the contents of elements with el's parent node's child elements, retaining relative order.

  4. For each child in elements:

    1. If child is el:

      1. Let source set be an empty source set.

      2. If child has a srcset or imagesrcset attribute, parse child's srcset attribute and set source set to the returned source set.

      3. Parse child's sizes attribute, and let source set's source size be the returned value.

      4. If child has a src or href attribute whose value is not the empty string and source set does not contain an image source with a pixel density descriptor value of 1, and no image source with a width descriptor, append child's src or href attribute value to source set.

      5. Normalize the source densities of source set.

      6. Let el's source set be source set.

      7. Return.

        If el is a link element, then elements contains only el, so this step will be reached immediately and the rest of the algorithm will not run.

    2. Assert: child is not a link element.

    3. If child is not a source element, continue to the next child. Otherwise, child is a source element.

    4. If child does not have a srcset attribute, continue to the next child.

    5. Parse child's srcset attribute and let the returned source set be source set.

    6. If source set has zero image sources, continue to the next child.

    7. If child has a media attribute, and its value does not match the environment, continue to the next child.

    8. Parse child's sizes attribute with the fallback width width, and let source set's source size be the returned value.

    9. If child has a type attribute, and its value is an unknown or unsupported MIME type, continue to the next child.

    10. Normalize the source densities of source set.

    11. Let el's source set be source set.

    12. Return.

Each img element independently considers its previous sibling source elements plus the img element itself for selecting an image source, ignoring any other (invalid) elements, including other img elements in the same picture element, or source elements that are following siblings of the relevant img element.

4.8.4.3.8 Parsing a srcset attribute

When asked to parse a srcset attribute from an element, parse the value of the element's srcset attribute as follows:

  1. Let input be the value passed to this algorithm.

  2. Let position be a pointer into input, initially pointing at the start of the string.

  3. Let candidates be an initially empty source set.

  4. Splitting loop: Collect a sequence of code points that are ASCII whitespace or U+002C COMMA characters from input given position. If any U+002C COMMA characters were collected, that is a parse error.

  5. If position is past the end of input, return candidates.

  6. Collect a sequence of code points that are not ASCII whitespace from input given position, and let that be url.

  7. Let descriptors be a new empty list.

  8. If url ends with U+002C (,), then:

    1. Remove all trailing U+002C COMMA characters from url. If this removed more than one character, that is a parse error.

    Otherwise:

    1. Descriptor tokenizer: Skip ASCII whitespace within input given position.

    2. Let current descriptor be the empty string.

    3. Let state be in descriptor.

    4. Let c be the character at position. Do the following depending on the value of state. For the purpose of this step, "EOF" is a special character representing that position is past the end of input.

      In descriptor

      Do the following, depending on the value of c:

      ASCII whitespace

      If current descriptor is not empty, append current descriptor to descriptors and let current descriptor be the empty string. Set state to after descriptor.

      U+002C COMMA (,)

      Advance position to the next character in input. If current descriptor is not empty, append current descriptor to descriptors. Jump to the step labeled descriptor parser.

      U+0028 LEFT PARENTHESIS (()

      Append c to current descriptor. Set state to in parens.

      EOF

      If current descriptor is not empty, append current descriptor to descriptors. Jump to the step labeled descriptor parser.

      Anything else

      Append c to current descriptor.

      In parens

      Do the following, depending on the value of c:

      U+0029 RIGHT PARENTHESIS ())

      Append c to current descriptor. Set state to in descriptor.

      EOF

      Append current descriptor to descriptors. Jump to the step labeled descriptor parser.

      Anything else

      Append c to current descriptor.

      After descriptor

      Do the following, depending on the value of c:

      ASCII whitespace

      Stay in this state.

      EOF

      Jump to the step labeled descriptor parser.

      Anything else

      Set state to in descriptor. Set position to the previous character in input.

      Advance position to the next character in input. Repeat this step.

      In order to be compatible with future additions, this algorithm supports multiple descriptors and descriptors with parens.

  9. Descriptor parser: Let error be no.

  10. Let width be absent.

  11. Let density be absent.

  12. Let future-compat-h be absent.

  13. For each descriptor in descriptors, run the appropriate set of steps from the following list:

    If the descriptor consists of a valid non-negative integer followed by a U+0077 LATIN SMALL LETTER W character
    1. If the user agent does not support the sizes attribute, let error be yes.

      A conforming user agent will support the sizes attribute. However, user agents typically implement and ship features in an incremental manner in practice.

    2. If width and density are not both absent, then let error be yes.

    3. Apply the rules for parsing non-negative integers to the descriptor. If the result is zero, let error be yes. Otherwise, let width be the result.

    If the descriptor consists of a valid floating-point number followed by a U+0078 LATIN SMALL LETTER X character
    1. If width, density and future-compat-h are not all absent, then let error be yes.

    2. Apply the rules for parsing floating-point number values to the descriptor. If the result is less than zero, let error be yes. Otherwise, let density be the result.

      If density is zero, the intrinsic dimensions will be infinite. User agents are expected to have limits in how big images can be rendered, which is allowed by the hardware limitations clause.

    If the descriptor consists of a valid non-negative integer followed by a U+0068 LATIN SMALL LETTER H character

    This is a parse error.

    1. If future-compat-h and density are not both absent, then let error be yes.

    2. Apply the rules for parsing non-negative integers to the descriptor. If the result is zero, let error be yes. Otherwise, let future-compat-h be the result.

    Anything else

    Let error be yes.

  14. If future-compat-h is not absent and width is absent, let error be yes.

  15. If error is still no, then append a new image source to candidates whose URL is url, associated with a width width if not absent and a pixel density density if not absent. Otherwise, there is a parse error.

  16. Return to the step labeled splitting loop.

4.8.4.3.9 Parsing a sizes attribute

When asked to parse a sizes attribute from an element, parse a comma-separated list of component values from the value of the element's sizes attribute (or the empty string, if the attribute is absent), and let unparsed sizes list be the result. [CSSSYNTAX]

For each unparsed size in unparsed sizes list:

  1. Remove all consecutive <whitespace-token>s from the end of unparsed size. If unparsed size is now empty, that is a parse error; continue to the next iteration of this algorithm.

  2. If the last component value in unparsed size is a valid non-negative <source-size-value>, let size be its value and remove the component value from unparsed size. Any CSS function other than the math functions is invalid. Otherwise, there is a parse error; continue to the next iteration of this algorithm.

  3. Remove all consecutive <whitespace-token>s from the end of unparsed size. If unparsed size is now empty, return size and exit this algorithm. If this was not the last item in unparsed sizes list, that is a parse error.

  4. Parse the remaining component values in unparsed size as a <media-condition>. If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue to the next iteration of this algorithm. [MQ]

  5. Return size and exit this algorithm.

If the above algorithm exhausts unparsed sizes list without returning a size value, then return 100vw.

While a valid source size list only contains a bare <source-size-value> (without an accompanying <media-condition>) as the last entry in the <source-size-list>, the parsing algorithm technically allows such at any point in the list, and will accept it immediately as the size if the preceding entries in the list weren't used. This is to enable future extensions, and protect against simple author errors such as a final trailing comma.

4.8.4.3.10 源像素密度规范化

image source 除 URL 之外可以有一个 像素密度描述符, 一个 宽度描述符 或者什么描述符都没有。 source set 规范化后会给每个 image source 一个 像素密度描述符

当要求 规范化 source set source set 的源像素密度时, 用户代理必须执行以下操作:

  1. source sizesource setsource size

  2. source set 中的每个 image source

    1. 如果 image source 有一个 像素密度描述符, 继续下一个 image source

    2. 否则,如果 image source 有一个 宽度描述符, 把 宽度描述符 替换为 像素密度描述符,其 宽度描述符的值 除以 源大小,单位是 x

      如果 源大小 是零,像素密度会是无穷大, 这会导致 固有尺寸 为 0 乘以 0。

    3. 否则,给出 image source像素密度描述符1x

4.8.4.3.11 Reacting to environment changes

The user agent may at any time run the following algorithm to update an img element's image in order to react to changes in the environment. (User agents are not required to ever run this algorithm; for example, if the user is not looking at the page any more, the user agent might want to wait until the user has returned to the page before determining which image to use, in case the environment changes again in the meantime.)

User agents are encouraged to run this algorithm in particular when the user changes the viewport's size (e.g. by resizing the window or changing the page zoom), and when an img element is inserted into a document, so that the density-corrected intrinsic width and height match the new viewport, and so that the correct image is chosen when art direction is involved.

  1. Await a stable state. The synchronous section consists of all the remaining steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)

  2. ⌛ If the img element does not use srcset or picture, its node document is not the active document, has image data whose resource type is multipart/x-mixed-replace, or the pending request is not null, then return.

  3. ⌛ Let selected source and selected pixel density be the URL and pixel density that results from selecting an image source, respectively.

  4. ⌛ If selected source is null, then return.

  5. ⌛ If selected source and selected pixel density are the same as the element's last selected source and current pixel density, then return.

  6. Parse selected source, relative to the element's node document, and let urlString be the resulting URL string. If that is not successful, then return.

  7. ⌛ Let corsAttributeState be the state of the element's crossorigin content attribute.

  8. ⌛ Let origin be the origin of the img element's node document.

  9. ⌛ Let client be the img element's node document's relevant settings object.

  10. ⌛ Let key be a tuple consisting of urlString, corsAttributeState, and, if corsAttributeState is not No CORS, origin.

  11. ⌛ Let image request be a new image request whose current URL is urlString

  12. ⌛ Let the element's pending request be image request.

  13. End the synchronous section, continuing the remaining steps in parallel.

  14. If the list of available images contains an entry for key, then set image request's image data to that of the entry. Continue to the next step.

    Otherwise:

    1. Let request be the result of creating a potential-CORS request given urlString, "image", and corsAttributeState.

    2. Set request's client to client, initiator to "imageset", and set request's synchronous flag.

    3. Set request's referrer policy to the current state of the element's referrerpolicy attribute.

    4. Let response be the result of fetching request.

    5. If response's unsafe response is a network error or if the image format is unsupported (as determined by applying the image sniffing rules, again as mentioned earlier), or if the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, or if the resource type is multipart/x-mixed-replace, then let pending request be null and abort these steps.

    6. Otherwise, response's unsafe response is image request's image data. It can be either CORS-same-origin or CORS-cross-origin; this affects the origin of the image itself (e.g., when used on a canvas).

  15. Queue an element task on the DOM manipulation task source given the img element and the following steps:

    1. If the img element has experienced relevant mutations since this algorithm started, then let pending request be null and abort these steps.

    2. Let the img element's last selected source be selected source and the img element's current pixel density be selected pixel density.

    3. Set the image request's state to completely available.

    4. Add the image to the list of available images using the key key, with the ignore higher-layer caching flag set.

    5. Upgrade the pending request to the current request.

    6. Update the img element's presentation appropriately.

    7. Fire an event named load at the img element.

4.8.4.4 为图片提供替代文字的要求
4.8.4.4.1 通用指引

除非另有说明,必须指定 alt 属性且它的值不能为空,且必须适合替代图片。 对 alt 属性具体的要求取决于它要表示什么图片,在下面给出描述。

编写替代文本时要考虑的最一般规则如下: 其目的是用其 alt 属性的文本替换每个图像不会改变页面的含义

所以,通常在编写替代文本时,考虑如果不能包含一个图片时会怎样写。

基于此的一个推论是 alt 属性的值不应该包含 图片的 caption, titlelegend 文本。 应该包含的替代文本是用于替代图片的;而不是图片的补充。 用 title 属性可以提供补充信息。

另一个推论是 alt 属性的值不应该重复已经由后面的文字提供的信息。

考虑替代文字的一种方式是,假设你在跟某人打电话, 这时如何直接读出这个包含图片的页面,而不用提这里有一张图片。 无论你说什么来替代图像,这通常都是编写替代文本的良好开端。

当创建 超链接a 元素或 button 元素 没有文本内容只包含一个或更多图片时,alt 属性必须包含一些文字来传达链接或按钮的用途。

在这个例子中,要求用户从三个颜色中选择一个喜欢的颜色。 每个颜色由图片给出,但对于用户代理配置为不显示图片的用户会用颜色名来替代:

<h1>Pick your color</h1>
<ul>
 <li><a href="green.html"><img src="green.jpeg" alt="Green"></a></li>
 <li><a href="blue.html"><img src="blue.jpeg" alt="Blue"></a></li>
 <li><a href="red.html"><img src="red.jpeg" alt="Red"></a></li>
</ul>

在这个例子中,每个按钮有很多图片来表示用户想要输出的颜色类型。 每种情况都用第一个图片提供替代文本。

<button name="rgb"><img src="red" alt="RGB"><img src="green" alt=""><img src="blue" alt=""></button>
<button name="cmyk"><img src="cyan" alt="CMYK"><img src="magenta" alt=""><img src="yellow" alt=""><img src="black" alt=""></button>

由于每个图片表示文字的一部分,也可以写成这样:

<button name="rgb"><img src="red" alt="R"><img src="green" alt="G"><img src="blue" alt="B"></button>
<button name="cmyk"><img src="cyan" alt="C"><img src="magenta" alt="M"><img src="yellow" alt="Y"><img src="black" alt="K"></button>

但是对于其他的替代文本,可能不能这样写,把所有替代文本放到每种情况的一张图片中可能更合理:

<button name="rgb"><img src="red" alt="sRGB profile"><img src="green" alt=""><img src="blue" alt=""></button>
<button name="cmyk"><img src="cyan" alt="CMYK profile"><img src="magenta" alt=""><img src="yellow" alt=""><img src="black" alt=""></button>
4.8.4.4.3 A phrase or paragraph with an alternative graphical representation: charts, diagrams, graphs, maps, illustrations

Sometimes something can be more clearly stated in graphical form, for example as a flowchart, a diagram, a graph, or a simple map showing directions. In such cases, an image can be given using the img element, but the lesser textual version must still be given, so that users who are unable to view the image (e.g. because they have a very slow connection, or because they are using a text-only browser, or because they are listening to the page being read out by a hands-free automobile voice web browser, or simply because they are blind) are still able to understand the message being conveyed.

The text must be given in the alt attribute, and must convey the same message as the image specified in the src attribute.

It is important to realize that the alternative text is a replacement for the image, not a description of the image.

In the following example we have a flowchart in image form, with text in the alt attribute rephrasing the flowchart in prose form:

<p>In the common case, the data handled by the tokenization stage
comes from the network, but it can also come from script.</p>
<p><img src="images/parsing-model-overview.svg" alt="The Network
passes data to the Input Stream Preprocessor, which passes it to the
Tokenizer, which passes it to the Tree Construction stage. From there,
data goes to both the DOM and to Script Execution. Script Execution is
linked to the DOM, and, using document.write(), passes data to the
Tokenizer."></p>

Here's another example, showing a good solution and a bad solution to the problem of including an image in a description.

First, here's the good solution. This sample shows how the alternative text should just be what you would have put in the prose if the image had never existed.

<!-- This is the correct way to do things. -->
<p>
 You are standing in an open field west of a house.
 <img src="house.jpeg" alt="The house is white, with a boarded front door.">
 There is a small mailbox here.
</p>

Second, here's the bad solution. In this incorrect way of doing things, the alternative text is simply a description of the image, instead of a textual replacement for the image. It's bad because when the image isn't shown, the text doesn't flow as well as in the first example.

<!-- This is the wrong way to do things. -->
<p>
 You are standing in an open field west of a house.
 <img src="house.jpeg" alt="A white house, with a boarded front door.">
 There is a small mailbox here.
</p>

Text such as "Photo of white house with boarded door" would be equally bad alternative text (though it could be suitable for the title attribute or in the figcaption element of a figure with this image).

4.8.4.4.4 带有替代图形表示的短语或标签:图标,徽标

一个文档可以包含图标信息,图标是为了帮助视觉浏览器的用户一目了然地识别功能。

有些情况下,图标是文本标签的补充,它们传达同样的含义。 那些情况下,alt 属性必须存在且为空。

下面的图标在文本旁边表达同样的含义,所以它们的 alt 属性为空:

<nav>
 <p><a href="/help/"><img src="/icons/help.png" alt=""> Help</a></p>
 <p><a href="/configure/"><img src="/icons/configuration.png" alt="">
 Configuration Tools</a></p>
</nav>

另外一些情况下,图标旁边没有文字来描述它的含义;这样的图标就应该解释自己的含义。 那些情况下,同等的文本标签必须通过alt 属性给出。

下面是一个新闻站点,每个文章用一个图标来表示对应的话题。

<body>
 <article>
  <header>
   <h1>Ratatouille wins <i>Best Movie of the Year</i> award</h1>
   <p><img src="movies.png" alt="Movies"></p>
  </header>
  <p>Pixar has won yet another <i>Best Movie of the Year</i> award,
  making this its 8th win in the last 12 years.</p>
 </article>
 <article>
  <header>
   <h1>Latest TWiT episode is online</h1>
   <p><img src="podcasts.png" alt="Podcasts"></p>
  </header>
  <p>The latest TWiT episode has been posted, in which we hear
  several tech news stories as well as learning much more about the
  iPhone. This week, the panelists compare how reflective their
  iPhones' Apple logos are.</p>
 </article>
</body>

许多页面包含标志(Logo),徽章,旗帜或徽记,代表某个特定实体,如公司,组织,项目,乐队,软件包,国家或某些特定实体。

如果标志(Logo)被用于表示实体,例如作为页面标题。 alt 属性必须包含由徽标表示的实体的名称。 alt 属性 不得 包含类似 “logo” 的文字,因为它传达的不是标志,而是实体本身。

如果标志(Logo)用在它表示的实体的名字旁边,那这个标志就是补充性的, 其 alt 属性必须为空。

如果标志(Logo)仅用作装饰材料(例如品牌标识,或者例如,作为提及徽标所属实体的文章中的配图),那么它适用下文的纯粹装饰性图片的条目。 如果实际上讨论的就是标志,那么它就用作了短语或段落(徽标的描述)并且有替代的图形表示(徽标本身),它适用上面的第一个条目。

在下面的代码片段中,上面四种情况都存在。首先这个标志用于表示一个公司:

<h1><img src="XYZ.gif" alt="The XYZ company"></h1>

然后下面的段落中,在公司名旁边使用标志,所以没有替代文本:

<article>
 <h2>News</h2>
 <p>We have recently been looking at buying the <img src="alpha.gif"
 alt=""> ΑΒΓ company, a small Greek company
 specializing in our type of product.</p>

在这第三个代码片段中,在边栏中有一个标志,作为一个大的讨论并购的文章的一部分:

 <aside><p><img src="alpha-large.gif" alt=""></p></aside>
 <p>The ΑΒΓ company has had a good quarter, and our
 pie chart studies of their accounts suggest a much bigger blue slice
 than its green and orange slices, which is always a good sign.</p>
</article>

最后,我们有一个意见部分谈论一个标志,因此在替代文本中细致地描述了这个标志。

<p>Consider for a moment their logo:</p>

<p><img src="/images/logo" alt="It consists of a green circle with a
green question mark centered inside it."></p>

<p>How unoriginal can you get? I mean, oooooh, a question mark, how
<em>revolutionary</em>, how utterly <em>ground-breaking</em>, I'm
sure everyone will rush to adopt those specifications now! They could
at least have tried for some sort of, I don't know, sequence of
rounded squares with varying shades of green and bold white outlines,
at least that would look good on the cover of a blue book.</p>

图片 不可用 时就会使用文本。 这个例子展示了替代文本应该怎样写,使得这些文本可以无缝地嵌入周围的文本, 就像那里从来没有图片一样。

4.8.4.4.5 Text that has been rendered to a graphic for typographical effect

Sometimes, an image just consists of text, and the purpose of the image is not to highlight the actual typographic effects used to render the text, but just to convey the text itself.

In such cases, the alt attribute must be present but must consist of the same text as written in the image itself.

Consider a graphic containing the text "Earth Day", but with the letters all decorated with flowers and plants. If the text is merely being used as a heading, to spice up the page for graphical users, then the correct alternative text is just the same text "Earth Day", and no mention need be made of the decorations:

<h1><img src="earthdayheading.png" alt="Earth Day"></h1>

An illuminated manuscript might use graphics for some of its images. The alternative text in such a situation is just the character that the image represents.

<p><img src="initials/o.svg" alt="O">nce upon a time and a long long time ago, late at
night, when it was dark, over the hills, through the woods, across a great ocean, in a land far
away, in a small house, on a hill, under a full moon...

When an image is used to represent a character that cannot otherwise be represented in Unicode, for example gaiji, itaiji, or new characters such as novel currency symbols, the alternative text should be a more conventional way of writing the same thing, e.g. using the phonetic hiragana or katakana to give the character's pronunciation.

In this example from 1997, a new-fangled currency symbol that looks like a curly E with two bars in the middle instead of one is represented using an image. The alternative text gives the character's pronunciation.

<p>Only <img src="euro.png" alt="euro ">5.99!

An image should not be used if characters would serve an identical purpose. Only when the text cannot be directly represented using text, e.g., because of decorations or because there is no appropriate character (as in the case of gaiji), would an image be appropriate.

If an author is tempted to use an image because their default system font does not support a given character, then web Fonts are a better solution than images.

4.8.4.4.6 A graphical representation of some of the surrounding text

In many cases, the image is actually just supplementary, and its presence merely reinforces the surrounding text. In these cases, the alt attribute must be present but its value must be the empty string.

In general, an image falls into this category if removing the image doesn't make the page any less useful, but including the image makes it a lot easier for users of visual browsers to understand the concept.

A flowchart that repeats the previous paragraph in graphical form:

<p>The Network passes data to the Input Stream Preprocessor, which
passes it to the Tokenizer, which passes it to the Tree Construction
stage. From there, data goes to both the DOM and to Script Execution.
Script Execution is linked to the DOM, and, using document.write(),
passes data to the Tokenizer.</p>
<p><img src="images/parsing-model-overview.svg" alt=""></p>

In these cases, it would be wrong to include alternative text that consists of just a caption. If a caption is to be included, then either the title attribute can be used, or the figure and figcaption elements can be used. In the latter case, the image would in fact be a phrase or paragraph with an alternative graphical representation, and would thus require alternative text.

<!-- Using the title="" attribute -->
<p>The Network passes data to the Input Stream Preprocessor, which
passes it to the Tokenizer, which passes it to the Tree Construction
stage. From there, data goes to both the DOM and to Script Execution.
Script Execution is linked to the DOM, and, using document.write(),
passes data to the Tokenizer.</p>
<p><img src="images/parsing-model-overview.svg" alt=""
        title="Flowchart representation of the parsing model."></p>
<!-- Using <figure> and <figcaption> -->
<p>The Network passes data to the Input Stream Preprocessor, which
passes it to the Tokenizer, which passes it to the Tree Construction
stage. From there, data goes to both the DOM and to Script Execution.
Script Execution is linked to the DOM, and, using document.write(),
passes data to the Tokenizer.</p>
<figure>
 <img src="images/parsing-model-overview.svg" alt="The Network leads to
 the Input Stream Preprocessor, which leads to the Tokenizer, which
 leads to the Tree Construction stage. The Tree Construction stage
 leads to two items. The first is Script Execution, which leads via
 document.write() back to the Tokenizer. The second item from which
 Tree Construction leads is the DOM. The DOM is related to the Script
 Execution.">
 <figcaption>Flowchart representation of the parsing model.</figcaption>
</figure>
<!-- This is WRONG. Do not do this. Instead, do what the above examples do. -->
<p>The Network passes data to the Input Stream Preprocessor, which
passes it to the Tokenizer, which passes it to the Tree Construction
stage. From there, data goes to both the DOM and to Script Execution.
Script Execution is linked to the DOM, and, using document.write(),
passes data to the Tokenizer.</p>
<p><img src="images/parsing-model-overview.svg"
        alt="Flowchart representation of the parsing model."></p>
<!-- Never put the image's caption in the alt="" attribute! -->

A graph that repeats the previous paragraph in graphical form:

<p>According to a study covering several billion pages,
about 62% of documents on the web in 2007 triggered the Quirks
rendering mode of web browsers, about 30% triggered the Almost
Standards mode, and about 9% triggered the Standards mode.</p>
<p><img src="rendering-mode-pie-chart.png" alt=""></p>
4.8.4.4.7 辅助性图片

有些图片对内容不那么重要,可能是纯粹装饰性图片,也可能与文本完全冗余。 这些情况下,alt 属性也必须存在,它的值应该是空字符串, 或者是一个图片传达的信息的文本表示。如果图片的标题部分给出了图片标题,那么 alt 属性值不得为空(因为那可能会让非视觉媒体的读者感到困惑)。

考虑一篇关于政治人物的新文章,其中的图片显示了人物的面部,通过样式表浮动到右侧。 这张图片就不是纯装饰性的,因为它与故事相关。这张图片也不完全与故事冗余,因为它显示了政客的长相。 是否提供替代文本取决于作者,也部分取决于这张图片是否对文章起到润色的作用。

下面第一个例子中,图片没有上下文也没有替代文本:

<p><img src="alexsalmond.jpeg" alt=""> Ahead of today's referendum,
the First Minister of Scotland, Alex Salmond, wrote an open letter to all
registered voters. In it, he admitted that all countries make mistakes.</p>

如果图片只是一张脸,可能没有必要描述它。 读者完全不关心他的头发是红色还是棕色,白皮肤或黑皮肤,有一个眼睛还是两个眼睛。

但是如果图片更加动态,比如显示了政客很生气,或者非常开心,或者很颓废, 可能就应该加一些替代文本来给文章一个基调。如果没有替代文本可能这个基调就会被读者遗漏。

<p><img src="alexsalmond.jpeg" alt="Alex Salmond is sad.">
Ahead of today's referendum, the First Minister of Scotland, Alex Salmond,
wrote an open letter to all registered voters. In it, he admitted that all
countries make mistakes.</p>
<p><img src="alexsalmond.jpeg" alt="Alex Salmond is ecstatic!">
Ahead of today's referendum, the First Minister of Scotland, Alex Salmond,
wrote an open letter to all registered voters. In it, he admitted that all
countries make mistakes.</p>

任务是 "伤心" 还是 "高兴" 会影响后续段落的解读: 他可能是说由于即将举行的公民投票会对他不利而向民众辞职, 也可能是说这次选举出了一些问题,但是接下来的投票率可能使它变得无关紧要。 解读因图片内容而异。

如果该图片有标题部分,那么包含一段替代文本可以避免让非视觉媒体的用户困惑标题指代的内容。

<p>Ahead of today's referendum, the First Minister of Scotland, Alex Salmond,
wrote an open letter to all registered voters. In it, he admitted that all
countries make mistakes.</p>
<figure>
 <img src="alexsalmond.jpeg"
      alt="A high forehead, cheerful disposition, and dark hair round out Alex Salmond's face.">
 <figcaption> Alex Salmond, SNP. Photo © 2014 PolitiPhoto. </figcaption>
</figure>
4.8.4.4.8 不提供任何信息的纯装饰性图片

如果图片是装饰性的而且不是页面特定的 — 比如这个图片作为站点设计的一部分。 — 那么这个图片应该通过站点 CSS 来指定,而不是写在文档标记中。

但是如果一张图片没有在周围的文字中加以讨论,但仍然有些关联,也可以使用 img 元素把它包含在页面中。这样的图片的 alt 属性必须存在而且值必须是空字符串。

有些关联的纯装饰性图片的例子比如,一篇介绍在 Burning Man 发生的事件的博文会引入一张 Black Rock City 景色的照片,或者在显示诗歌的页面上引入一张受这首诗启发的绘画作品。 下面的代码片段是第二种情况的例子(代码中只引入了诗歌的第一小节):

<h1>The Lady of Shalott</h1>
<p><img src="shalott.jpeg" alt=""></p>
<p>On either side the river lie<br>
Long fields of barley and of rye,<br>
That clothe the wold and meet the sky;<br>
And through the field the road run by<br>
To many-tower'd Camelot;<br>
And up and down the people go,<br>
Gazing where the lilies blow<br>
Round an island there below,<br>
The island of Shalott.</p>

当一张图片被切分为若干个小图片文件,用来拼装成原来的大图时,这些图片中要有一个的 alt 属性按照相关规则设置为大图的替代文本。 然后其他所有剩余图片必须把 alt 属性设为空字符串。

下面的例子中,表示 XYZ Corp 公司 Logo 的图片被分为两部分, 第一个包含字母 "XYZ" 第二个包含单词 "Corp"。 都包含在了第一个图片的替代文本("XYZ Corp")中。

<h1><img src="logo1.png" alt="XYZ Corp"><img src="logo2.png" alt=""></h1>

下面的例子中,评分显示为三颗星星和两颗空星。 虽然替代文本可以是 "★★★☆☆",但作者决定提供更有帮助的评分格式比如 "3 / 5"。它设置为第一个图片的替代文本。其他图片的替代文本为空。

<p>Rating: <meter max=5 value=3><img src="1" alt="3 out of 5"
  ><img src="1" alt=""><img src="1" alt=""><img src="0" alt=""
  ><img src="0" alt=""></meter></p>

通常带连接的图片应该使用 图片映射 而不是切分图片。

但是,如果图片确实已经被切分了,而且切分后的部分是链接的唯一内容, 那么每个链接必须有一个图片必须把它的 alt 属性设置为表示链接用途的替代文本。

下面的例子是一张表示飞行面条怪物徽章的图片,左右两侧的面条状物是单独的两张图片, 这样用户就可以在探险中选择左右两侧的图片了。

<h1>The Church</h1>
<p>You come across a flying spaghetti monster. Which side of His
Noodliness do you wish to reach out for?</p>
<p><a href="?go=left" ><img src="fsm-left.png"  alt="Left side. "></a
  ><img src="fsm-middle.png" alt=""
  ><a href="?go=right"><img src="fsm-right.png" alt="Right side."></a></p>
4.8.4.4.11 内容的关键部分

有些情况下,图片是内容的关键部分。比如照片库页面中的图片就是这样的情况。 这时图片就是包含它的页面的重点。

如何为内容关键的图片提供替代文本取决于图片的出处。

通常情况

如果可以提供详细的替代文本,如果图像是杂志评论中的一系列截图的一部分,或者是连环漫画的一部分, 或者是关于该照片的博客文章中的那个照片,则必须通过 alt 属性给出替代图片的文字。

新操作系统的屏幕截图,其中包含一些替代文字:

<figure>
 <img src="KDE%20Light%20desktop.png"
      alt="The desktop is blue, with icons along the left hand side in
           two columns, reading System, Home, K-Mail, etc. A window is
           open showing that menus wrap to a second line if they
           cannot fit in the window. The window has a list of icons
           along the top, with an address bar below it, a list of
           icons for tabs along the left edge, a status bar on the
           bottom, and two panes in the middle. The desktop has a bar
           at the bottom of the screen with a few buttons, a pager, a
           list of open applications, and a clock.">
 <figcaption>Screenshot of a KDE desktop.</figcaption>
</figure>

财务报告中的图表:

<img src="sales.gif"
     title="Sales graph"
     alt="From 1998 to 2005, sales increased by the following percentages
     with each year: 624%, 75%, 138%, 40%, 35%, 9%, 21%">

请注意,“销售图”对于销售图而言是不充分的替代文本。 做 标题 很好的文本通常不适合做替代文本。

难以提供完整描述的图片

有些情况下图片的特性决定了提供完整的替代文本不现实。 例如,图像可能模糊不清,或者可能是复杂的分形,或者可能是详细的地形图。

这些情况下 alt 属性也必须包含一些适当的替代文本, 但可以比较简短。

有时候根本无法用文字对图片做出正确的描述。例如对罗夏墨迹测验就无法提供有用的描述。 但是,即使是一个简单的描述也比什么都没有要好:

<figure>
 <img src="/commons/a/a7/Rorschach1.jpg" alt="A shape with left-right
 symmetry with indistinct edges, with a small gap in the center, two
 larger gaps offset slightly from the center, with two similar gaps
 under them. The outline is wider in the top half than the bottom
 half, with the sides extending upwards higher than the center, and
 the center extending below the sides.">
 <figcaption>A black outline of the first of the ten cards
 in the Rorschach inkblot test.</figcaption>
</figure>

注意下面是一个替代文本的非常糟糕的使用方式:

<!-- This example is wrong. Do not copy it. -->
<figure>
 <img src="/commons/a/a7/Rorschach1.jpg" alt="A black outline
 of the first of the ten cards in the Rorschach inkblot test.">
 <figcaption>A black outline of the first of the ten cards
 in the Rorschach inkblot test.</figcaption>
</figure>

这样把标题放到替代文字中根本没用,因为对于没有图片的用户它只是重复了标题, 相比于只读到或听到一次标题,再来重复一次根本不会有任何帮助。

无法描述的图片的另一个例子是分型,根据定义它的细节是无限的。

下面的例子展示了为曼德博集合提供替代文字的一种可能的方式。

<img src="ms1.jpeg" alt="The Mandelbrot set appears as a cardioid with
its cusp on the real axis in the positive direction, with a smaller
bulb aligned along the same center line, touching it in the negative
direction, and with these two shapes being surrounded by smaller bulbs
of various sizes.">

类似地,在生物学中人脸的照片也是内容的关键部分,也很难完全用文字替代:

<section class="bio">
 <h1>A Biography of Isaac Asimov</h1>
 <p>Born <b>Isaak Yudovich Ozimov</b> in 1920, Isaac was a prolific author.</p>
 <p><img src="headpics/asimov.jpeg" alt="Isaac Asimov had dark hair, a tall forehead, and wore glasses.
 Later in life, he wore long white sideburns.">
 <p>Asimov was born in Russia, and moved to the US when he was three years old.</p>
 <p>...
</section>

在这样的情况下,在替代文本中引述图片本身是不必要的(并且实际上不鼓励), 因为这样的文本与浏览器自身的图片报告是冗余的。 例如,如果替代文本是“Isaac Asimov的照片”,那么标准的用户代理可能将其读作 “(Image)Isaac Asimov 的照片” 而不是(更有用) “(Image)Isaac Asimov 是黑发 ,额头很高,戴着眼镜......”。

未知内容的图片

有些情况比较不幸,根本没有替代文字。可能是因为图片是动态获取的且没有关联的替代文本 (比如 Web 摄像头),也可能因为页面是由用户提供的图片通过脚本生成的, 而用户并没有提供合适的可用替代文本(例如照片分享站点), 也可能是因为作者自己不知道图片表示着什么(比如一个盲人摄影师在博客上分享了一张图片)。

这种情况下,alt 属性可以忽略,但必须符合以下条件之一:

这种情况应该保持在最低限度。只要作者有能力提供真正的替代文本, 那么忽略 alt 属性就是不可接受的。

如果一个照片分享网站收到图片时除了标题没有其他任何元数据, 这个照片可以这样标记:

<figure>
 <img src="1100670787_6a7c664aef.jpg">
 <figcaption>Bubbles traveled everywhere with us.</figcaption>
</figure>

当然如果能详细描述图片的重要部分,并通过替代文本提供出来会更好。

一个盲人的博客中,显示了一张用户拍的照片。刚开始用户可能不知道他们拍的照片上有什么:

<article>
 <h1>I took a photo</h1>
 <p>I went out today and took a photo!</p>
 <figure>
  <img src="photo2.jpeg">
  <figcaption>A photograph taken blindly from my front porch.</figcaption>
 </figure>
</article>

最后如果用户从他们的朋友那里得到了图片的描述,他们就可以包含一些替代文本:

<article>
 <h1>I took a photo</h1>
 <p>I went out today and took a photo!</p>
 <figure>
  <img src="photo2.jpeg" alt="The photograph shows my squirrel
  feeder hanging from the edge of my roof. It is half full, but there
  are no squirrels around. In the background, out-of-focus trees fill the
  shot. The feeder is made of wood with a metal grate, and it contains
  peanuts. The edge of the roof is wooden too, and is painted white
  with light blue streaks.">
  <figcaption>A photograph taken blindly from my front porch.</figcaption>
 </figure>
</article>

有时图片的整个意义就是没有文本描述,要用户为它提供描述。 例如,CAPTCHA 图片的目的就是看用户能否从用文字描述图形。 下面是标记 CAPTCHA 的一种方式(注意 title 属性):

<p><label>What does this image say?
<img src="captcha.cgi?id=8934" title="CAPTCHA">
<input type=text name=captcha></label>
(If you cannot see the image, you can use an <a
href="?audio">audio</a> test instead.)</p>

另一个例子是显示图片并询问替代文本的软件,这些文本之后会被写入到页面中。 这样的页面可能会有一个图片表格,像这样:

<table>
 <thead>
  <tr> <th> Image <th> Description
 <tbody>
  <tr>
   <td> <img src="2421.png" title="Image 640 by 100, filename 'banner.gif'">
   <td> <input name="alt2421">
  <tr>
   <td> <img src="2422.png" title="Image 200 by 480, filename 'ad3.gif'">
   <td> <input name="alt2422">
</table>

注意即使在这个例子中,在 title 属性中还是提供了尽可能多的有用信息。

因为有些用户根本不能使用照片 (比如因为他们的网络很慢,或因为他们在使用文本浏览器,或者因为他们正在听汽车的语音 Web 浏览器阅读页面内容,或者只是因为他们是盲人), 只在没有可用的替代文本而且没人可以提供时,才允许忽略 alt 属性。 作者没有付出努力不是一个可以接受的理由。

4.8.4.4.12 不是给用户看的图片

通常作者应该避免使用不用来显示的 img 元素。

如果一个 img 元素不是用于显示的,比如用于计算页面浏览量的服务。 那么 alt 属性必须为空字符串。

在这些场景下,widthheight 属性必须设为 0。

4.8.4.4.13 An image in an email or private document intended for a specific person who is known to be able to view images

This section does not apply to documents that are publicly accessible, or whose target audience is not necessarily personally known to the author, such as documents on a web site, emails sent to public mailing lists, or software documentation.

When an image is included in a private communication (such as an HTML email) aimed at a specific person who is known to be able to view images, the alt attribute may be omitted. However, even in such cases authors are strongly urged to include alternative text (as appropriate according to the kind of image involved, as described in the above entries), so that the email is still usable should the user use a mail client that does not support images, or should the document be forwarded on to other users whose abilities might not include easily seeing images.

4.8.4.4.14 Guidance for markup generators

Markup generators (such as WYSIWYG authoring tools) should, wherever possible, obtain alternative text from their users. However, it is recognized that in many cases, this will not be possible.

For images that are the sole contents of links, markup generators should examine the link target to determine the title of the target, or the URL of the target, and use information obtained in this manner as the alternative text.

For images that have captions, markup generators should use the figure and figcaption elements, or the title attribute, to provide the image's caption.

As a last resort, implementers should either set the alt attribute to the empty string, under the assumption that the image is a purely decorative image that doesn't add any information but is still specific to the surrounding content, or omit the alt attribute altogether, under the assumption that the image is a key part of the content.

Markup generators may specify a generator-unable-to-provide-required-alt attribute on img elements for which they have been unable to obtain alternative text and for which they have therefore omitted the alt attribute. The value of this attribute must be the empty string. Documents containing such attributes are not conforming, but conformance checkers will silently ignore this error.

This is intended to avoid markup generators from being pressured into replacing the error of omitting the alt attribute with the even more egregious error of providing phony alternative text, because state-of-the-art automated conformance checkers cannot distinguish phony alternative text from correct alternative text.

Markup generators should generally avoid using the image's own file name as the alternative text. Similarly, markup generators should avoid generating alternative text from any content that will be equally available to presentation user agents (e.g., web browsers).

This is because once a page is generated, it will typically not be updated, whereas the browsers that later read the page can be updated by the user, therefore the browser is likely to have more up-to-date and finely-tuned heuristics than the markup generator did when generating the page.

4.8.4.4.15 规范检查工具指引

规范检查工具必须把缺少 alt 属性报告为错误, 符合以下条件之一的情形除外: