Image Tag

Pictures are an important part of the Internet, making web pages colorful. This chapter introduces how to insert pictures into web pages.


The <img> tag is used to insert pictures. It is used alone and has no closing label.

<img src="foo.jpg" />

The above code inserts a picture foo.jpg into the web page. The src attribute specifies the URL of the picture. The above example is a relative URL, which means that the picture and the webpage are in the same directory.

<img> is an inline element by default, which is on the same line as the text before and after it.

<p>Hello<img src="foo.jpg" />World</p>

The rendering result of the above code is that the text and image are displayed on the same line.

The image is displayed in its original size by default. If the picture is very large and on the same line as the text, the picture will prop up the current line and the bottom edge of the picture and the bottom edge of the text will be on the same horizontal line.

<img> can be placed inside the <a> tag, making the image a clickable link.

<a href="example.html">
  <img src="foo.jpg" />

In the above code, the picture can be clicked like a link, and a jump will occur after clicking.

(1) alt attribute

The alt attribute is used to set the text description of the image. When the picture is not displayed (for example, the download fails, or the user closes the picture loading), the text will be displayed in the position of the picture.

<img src="foo.jpg" alt="sample image" />

In the above code, alt is the description of the picture. When the picture download fails, the browser will display the text "Sample Picture" in the place of the picture.

(2) width property, height property

The picture is inserted into the web page in its original size by default. The width and height properties can specify the width and height of the picture when it is displayed, in pixels or percentages.

<img src="foo.jpg" width="400" height="300" />

In the above code, the width property specifies that the width of the image display is 400 pixels, and the height property specifies that the display height is 300 pixels.

Note that once these two properties are set, the browser will leave a space of this size in the web page in advance, regardless of whether the image is loaded successfully. However, since the display size of the picture can be set with CSS, it is not recommended to use these two properties.

A special case is that only one of the width property and the height property is set, and the other is not set. At this time, the browser will automatically set the corresponding ratio of the image width or height according to the original size of the image. For example, if the image size is 800 pixels x 800 pixels, and the width property is set to 200, the browser will automatically set height to 200.

(3) srcset, sizes

See the "Responsive Image" section below for details.

(4) referrerpolicy

The HTTP request for image loading caused by <img> will carry the header information of Referer by default. The referrerpolicy attribute sets this behavior.

(5) crossorigin

Sometimes, the image and the webpage belong to different websites, and the loading of the image on the webpage will cause a cross-domain request, and the other party's server may require cross-domain authentication. The crossorigin attribute is used to tell the browser whether to download images in a cross-domain format, which is not used by default.

Simply put, as long as this property is turned on, the origin field will be added to the header information of the HTTP request, giving the domain name of the request, and it will not be added if this property is not turned on.

Once the property is turned on, it can be set to two values.

-anonymous: Cross-domain requests do not carry user credentials (usually cookies). -use-credentials: Cross-domain requests with user credentials.

Below is an example.

<img src="foo.jpg" crossorigin="anonymous" />

If the crossorigin attribute omits the value part, it is equivalent to anonymous.

<img src="foo.jpg" crossorigin />

(6) loading

The default behavior of the browser is to start loading the image as soon as the <img> tag is parsed. For very long web pages, this is a waste of bandwidth, because users may not scroll down and see the end of the web page all the time. The user is likely to click on the webpage and turn it off after viewing it for a while. The traffic for loading pictures that are not in the viewport is wasted.

The loading property changes this behavior. You can specify lazy loading of images, that is, images are not loaded by default, and will only be loaded when they are about to scroll into the viewport and become visible to the user, which saves bandwidth.

The loading attribute can take the following three values.

-auto: The default behavior of the browser, which is equivalent to not using the loading attribute. -lazy: Enable lazy loading. -eager: Load the resource immediately, no matter where it is on the page.

<img src="image.png" loading="lazy" alt="..." width="200" height="200" />

Due to the lazy loading of inline pictures, it may cause page layout rearrangement, so when using this attribute, it is best to specify the height and width of the picture.

<figure>, <figcaption>

The <figure> tag can be understood as an image block, encapsulating the image and related information together. <figcaption> is its optional child element, which represents the text description of the image. It is usually used to place the title, and there can be more than one.

  <img src="" />
  <figcaption>Sample image</figcaption>

In addition to images, <figure> can also encapsulate introductions, codes, poems, etc. It is equivalent to a semantic container that encapsulates the main content and additional information.

  <figcaption>JavaScript code example</figcaption>
  <p><code>const foo ='hello';</code></p>

Responsive image

Web pages can produce good display effects on devices of different sizes, which is called "responsive design"(responsive web design) . The webpage image of responsive design is the "responsive image" (responsive image).

There are many solutions for responsive images, both JavaScript and CSS can be implemented. Only the HTML method with the best semantics is introduced here, which is natively supported by the browser.

Origin of the problem

We know that the <img> tag is used to insert webpage images, and in all cases the same image is inserted by default.

<img src="foo.jpg" />

The above code is inserted into the image file foo.jpg on the desktop and mobile phones.

Although this method is simple, it has three major drawbacks.

(1) Volume

Generally speaking, large-size images are displayed on the desktop, and the file size is relatively large. The screen of the mobile phone is small, and only a small size image is needed, which can save bandwidth and accelerate the rendering of web pages.

(2) Pixel density

Desktop displays generally have a single pixel density, while the display of a mobile phone often has a multiple pixel density, that is, multiple pixels are combined into one pixel during display. This screen is called a Retina screen. The image file is likely to be very clear on the desktop, and it will be a bit blurry when placed on the phone, because the image does not have such a high pixel density, the browser automatically copies each pixel of the image to the surrounding pixels to meet the pixel density requirements, resulting in the image The sharpness has decreased.

(3) Visual style

The desktop monitor has a larger area and the image can accommodate more details. The screen of the mobile phone is small, and many details are not clear, so the key points need to be highlighted.

After the two pictures above and the phone picture below are cropped, the focus of the image is more prominent, and the effect is obviously better.

srcset attribute

In order to solve the above problems, HTML language provides a complete solution. First, the <img> tag introduces the srcset attribute.

The srcset attribute is used to specify multiple images to adapt to screens with different pixel densities. Its value is a comma-separated string, each part is an image URL, followed by a space, and then a pixel density descriptor. Please see the example below.

  srcset="foo-320w.jpg, foo-480w.jpg 1.5x, foo-640w.jpg 2x"

In the above code, the srcset attribute gives three image URLs, adapting to three different pixel densities.

The pixel density descriptor behind the image URL, the format is pixel density multiple + letter x. 1x means single pixel density and can be omitted. The browser selects the image to be loaded according to the pixel density of the current device.

If the srcset attribute does not satisfy the condition, then the default image specified by the src attribute is loaded.

sizes attribute

The pixel density adaptation is only suitable for images of the same size as the display area. If you want different sizes of screens to display images of different sizes, the srcset attribute is not enough, you must match the sizes attribute.

In the first step, the srcset attribute lists all available images.

    foo-160.jpg   160w,
    foo-320.jpg   320w,
    foo-640.jpg   640w,
    foo-1280.jpg 1280w

In the above code, the srcset attribute lists four available images, and the URL of each image is followed by a space, plus a width descriptor.

The width descriptor is the original width of the image, plus the character w. The original widths of the four pictures in the above example are 160 pixels, 320 pixels, 640 pixels, and 1280 pixels, respectively.

In the second step, the sizes property lists the image display width of different devices.

The value of the sizes attribute is a comma-separated string. Except for the last part, each part in front is a media query expression in parentheses, followed by a space, plus the display width of the image.

    foo-160.jpg   160w,
    foo-320.jpg   320w,
    foo-640.jpg   640w,
    foo-1280.jpg 1280w
  sizes="(max-width: 440px) 100vw,
            (max-width: 900px) 33vw,

In the above code, the sizes property gives three screen conditions and the corresponding image display width. For devices with a width of no more than 440 pixels, the image display width is 100%; for devices with a width of 441 pixels to 900 pixels, the image display width is 33%; for devices with a width of 900 pixels or more, the image display width is 254px.

In the third step, the browser obtains the display width of the image from the sizes attribute according to the width of the current device, and then finds the image closest to the width from the srcset attribute and loads it.

Assuming that the screen width of the current device is 480px, and the browser obtains it from the sizes property query, the display width of the picture is 33vw (ie 33%), which is equal to 160px. In the srcset attribute, there happens to be a picture with a width equal to 160px, so foo-160.jpg is loaded.

If the sizes attribute is omitted, the browser will select the closest image from the srcset attribute according to the actual image display width. Once the sizes attribute is used, it must be used in conjunction with the srcset attribute. Using the sizes attribute alone is invalid.


Responsive usage

The srcset attribute and the sizes attribute of the <img> tag solve the adaptation of pixel density and screen size respectively, but if you want to adapt to screens of different pixel densities and sizes at the same time, you must use <picture > label.

<picture> is a container tag that uses <source> and <img> internally to specify the images to be loaded in different situations.

  <source media="(max-width: 500px)" srcset="cat-vertical.jpg" />
  <source media="(min-width: 501px)" srcset="cat-horizontal.jpg" />
  <img src="cat.jpg" alt="cat" />

In the above code, there are two <source> tags and one <img> tag inside the <picture> tag.

The <source> tag inside <picture> mainly uses the media attribute and the srcset attribute. The media attribute gives the media query expression, and the srcset attribute is the srcset attribute of the <img> tag, giving the loaded image file. The sizes attribute can actually be used here, but because of the media attribute, it is not necessary.

The browser judges whether the current device satisfies the media query expression of the media attribute in the order in which the <source> tags appear, and if it is satisfied, it loads the image file specified by the srcset attribute, and does not execute the following < source> tag and <img> tag.

The <img> tag is an image loaded by default, which is used to satisfy all the above cases where <source> does not match, or old browsers that do not support <picture>.

In the above example, if the device width does not exceed 500px, load the image in the vertical screen, otherwise load the image in the horizontal screen.

An example is given below, taking into account the adaptation of screen size and pixel density.

    srcset="homepage-person@desktop.png, homepage-person@desktop-2x.png 2x"
    media="(min-width: 990px)"
    srcset="homepage-person@tablet.png, homepage-person@tablet-2x.png 2x"
    media="(min-width: 750px)"
    srcset="homepage-person@mobile.png, homepage-person@mobile-2x.png 2x"
    alt="Shopify Merchant, Corrine Anestopoulos"

In the above code, the media attribute of the <source> tag gives the adaptation conditions of the screen size, and each condition uses the srcset attribute, and then gives the image URL with two pixel densities.

Image format selection

In addition to responsive images, the <picture> tag can also be used to select images in different formats. For example, if the current browser supports the Webp format, load the image in this format, otherwise load the PNG image.

  <source type="image/svg+xml" srcset="logo.xml" />
  <source type="image/webp" srcset="logo.webp" />
  <img src="logo.png" alt="ACME Corp" />

In the above code, the type attribute of the <source> tag gives the MIME type of the image, and srcset is the corresponding image URL.

The browser checks whether it supports the image format specified by the type attribute in the order in which the <source> tags appear, and loads the image if it supports it, and no longer checks the following <source> tags. In the above example, the priority order of image loading is svg format, webp format and png format.