The HTML img tag

By

Learn how to use the HTML img tag with src, alt, width, height, loading, srcset, and sizes, including the CSS needed to make images responsive.

~~~

The HTML img tag adds an image to a page.

At minimum, provide the image URL with src and describe the image with alt:

<img src="dog.jpg" alt="A brown dog running on the beach">

img is a void element, so it does not have a closing tag.

What does the alt attribute do?

The alt text replaces the image when someone cannot see it. Screen readers use it, and browsers display it when the image fails to load.

Describe the image’s purpose, not every visual detail. If an image is purely decorative, use an empty value:

<img src="separator.svg" alt="">

Do not omit alt. An empty alt value tells assistive technology to ignore the image. A missing attribute does not.

Set the image width and height

Add the image’s intrinsic dimensions using width and height:

<img
  src="dog.jpg"
  alt="A brown dog running on the beach"
  width="1200"
  height="800"
>

These attributes give the browser the image’s aspect ratio before the file loads. This reserves the right amount of space and helps prevent layout shifts.

The CSS still controls the rendered size. To stop a large image from overflowing its container, use:

img {
  max-width: 100%;
  height: auto;
}

max-width: 100% lets the image shrink with its container. height: auto preserves its aspect ratio.

Lazy-load images below the fold

Add loading="lazy" to images that start outside the visible part of the page:

<img
  src="dog.jpg"
  alt="A brown dog running on the beach"
  width="1200"
  height="800"
  loading="lazy"
>

Avoid lazy-loading the main image visible at the top of the page. The browser should fetch that image immediately.

Responsive images with srcset

Use srcset when the same image is available at multiple widths:

<img
  src="dog-1200.jpg"
  alt="A brown dog running on the beach"
  width="1200"
  height="800"
  srcset="
    dog-480.jpg 480w,
    dog-800.jpg 800w,
    dog-1200.jpg 1200w
  "
  sizes="(max-width: 600px) 100vw, 800px"
>

The 480w, 800w, and 1200w values describe each file’s intrinsic width. They do not describe viewport breakpoints.

The sizes attribute describes how wide the image will be in the layout. In this example it uses the full viewport width up to 600px, then a maximum slot width of 800px.

The browser combines srcset, sizes, the viewport width, and the screen’s pixel density to choose an image. You provide the candidates; the browser chooses the best one.

Use the picture tag instead when you need different crops or formats rather than different sizes of the same image.

Tagged: HTML · All topics
~~~

Related posts about html: