Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 122 Β· Images and Media

Images

Add images with the HTML img element. Write useful alt text, set width and height to stop layout shift, pick the right format and lazy-load images.

Pictures turn a wall of text into a page people want to read. In HTML, almost every picture arrives through one small element: <img>. It is easy to use, but the details decide whether your page is fast, stable and usable for everyone.

In this lesson you will learn how <img> works, how to write alternative text that actually helps, why width and height still matter in a world of responsive layouts, which file format to choose, and how to stop off-screen images from slowing your page down.

The <img> element

<img> is a void element: it has no closing tag and no content. Everything it needs comes from attributes. Two of them matter on every single image:

  • src β€” the URL of the image file. It can be relative (photos/cat.jpg) or absolute (/samples/sunset.svg). The file paths lesson explains the difference.
  • alt β€” a text alternative that stands in for the image when it cannot be seen.
HTML
<img src="/samples/sunset.svg" alt="A yellow sun setting behind two green hills">

By default an image is inline: it sits on a line of text like a very large letter. That is why an image placed inside a paragraph flows with the words around it. You will learn more about this in Block and Inline Elements.

Your first image

Writing good alt text

The alt attribute is not a caption and not a place for keywords. It is the image's replacement. Screen readers announce it, browsers display it when the file fails to load, and search engines use it to understand the picture.

A practical test: imagine reading the page aloud to someone over the phone. When you reach the image, what would you say so they miss nothing important? That sentence is your alt text.

What you write depends on why the image is there:

Purpose of the image What alt should say Example
Informative photo or illustration The essential content, briefly alt="A cyclist crossing a rope bridge in heavy fog"
Image inside a link or button Where the link goes or what the button does alt="Home" on a logo that links to the home page
Image of text The same text alt="Summer sale: 30% off all tents"
Chart or diagram The key takeaway (with full details nearby) alt="Sales grew every month from January to May"
Purely decorative Nothing: alt="" A flourish between sections

A few habits make a big difference:

  • Skip "image of" and "picture of". Screen readers already announce that it is an image.
  • Be concise. One sentence is usually enough. Long explanations belong in the page text or a caption.
  • Do not repeat nearby text. If the image's content is already described right next to it, a shorter alt (or alt="") avoids saying the same thing twice.

Decorative images: alt=""

Some images add nothing but mood: a swirl, a background texture, an icon next to a word that already says the same thing. Give them an empty alt:

HTML
<img src="divider-swirl.svg" alt="">

An empty alt tells assistive technology to skip the image entirely. That is very different from leaving alt out. Without the attribute, many screen readers fall back to reading the file name β€” "divider dash swirl dot svg" β€” which is noise at best.

Never leave alt off. Use real text for meaningful images and alt="" for decorative ones. A missing alt is one of the most common accessibility failures on the web, and HTML validators flag it.

When images fail to load

width, height and layout shift

Images download after the HTML. If the browser does not know how big an image will be, it reserves no space for it. When the file finally arrives, everything below jumps down. This jump is called layout shift, and it is why you sometimes tap the wrong link on a page that is still loading.

The fix is simple: set width and height to the image's real pixel dimensions, as plain numbers without units.

HTML
<img src="team-photo.jpg" alt="Our five-person team on the office roof" width="1200" height="800">

"But my layout is responsive, so the image will not be 1200 pixels wide!" That is fine. Modern browsers use the two numbers to calculate the image's aspect ratio (here 3:2). Combine them with this common CSS rule and the image scales to fit its container while the browser still reserves exactly the right amount of space:

CSS
img {
  max-width: 100%;
  height: auto;
}
Reserved space vs. layout shift

Watch the second box: its paragraph sits right under the heading at first, then gets shoved down when the image arrives. The first box kept a gray placeholder of the right shape the whole time.

Choosing an image format

The src can point to many kinds of files. Each format has a sweet spot:

Format Best for Notes
JPEG Photos Lossy compression, no transparency. Supported everywhere.
PNG Screenshots, graphics with sharp edges, transparency Lossless, so photos become very large.
GIF Tiny, simple animations (legacy) Only 256 colors per frame. A short <video> is usually far smaller.
SVG Logos, icons, diagrams Vector: sharp at any size, often tiny. Covered in SVG Basics.
WebP Photos and graphics Usually 25–35% smaller than JPEG or PNG; supports transparency and animation.
AVIF Photos and graphics Often smaller still than WebP; supported by all current major browsers.

A sensible default today: SVG for anything drawn (logos, icons, charts), and WebP or AVIF for photos, with a JPEG fallback if you must support very old browsers. The Responsive Images lesson shows how <picture> lets the browser pick the best format it understands.

Lazy loading and decoding

A long article might contain thirty images, but the reader only sees two or three when the page opens. Downloading the rest straight away wastes data and competes with the content people are actually looking at.

Add loading="lazy" and the browser waits until the image is close to the viewport before fetching it:

HTML
<img src="gallery-07.webp" alt="A red kayak on a calm lake at dawn" width="800" height="533" loading="lazy">

The default value is loading="eager" (load immediately). Two rules of thumb:

  • Lazy-load images below the fold β€” the ones a visitor must scroll to reach.
  • Never lazy-load the main image at the top of the page. It is probably the most important thing on screen, and delaying it makes the page feel slower.

Lazy loading needs width and height even more than usual: without reserved space, a column of lazy images collapses to zero height and the browser may think they are all "near the viewport".

Lazy loading in action

There is also a decoding attribute. Decoding is the step where the browser turns compressed bytes into pixels. decoding="async" hints that the browser may do this off the main thread without holding up other content; sync asks for the opposite; auto (the default) lets the browser decide. Modern browsers already make good choices, so you rarely need it β€” but you will see it in the wild.

More loading tools. The fetchpriority="high" attribute can make the browser fetch your most important image sooner. You will meet it, along with preloading, in Loading Resources Efficiently.

Wrap an <img> in an <a> to make it clickable. When an image is the only content of a link, its alt text becomes the link's name, so describe the destination, not the picture:

HTML
<a href="/">
  <img src="logo.svg" alt="Northwind Books home page" width="140" height="40">
</a>

If the link also contains visible text, the image is usually decorative and gets alt="", because the text already names the destination. Two small habits make image links pleasant to use:

  • Style the link, not the image, for focus: a:focus-visible img { outline: 3px solid #2563eb; } lets keyboard users see where they are.
  • Make the clickable area big enough for a thumb. A 16-pixel icon is hard to hit, so pad the link instead of enlarging the picture.

Aligning images

Old pages aligned pictures with <img align="right">. That attribute is obsolete (see Deprecated and Obsolete Features); use CSS instead. Three tools cover almost every case:

  • float makes text wrap around a picture, like a photo in a magazine article.
  • margin-inline: auto with display: block centers an image on its own line.
  • Flexbox or grid place an image next to text in a row, with full control over gaps and alignment.
Float, center and flex

A floated image leaves the normal flow. If the text beside it is shorter than the picture, the next block can slide up next to it; clear: both (as on the <hr> above) or a wrapper with display: flow-root contains the float.

Animated images

Browsers can animate several image formats inside a plain <img>, with no script:

Format Notes
GIF Universal, but limited to 256 colors and usually large for what it shows.
APNG Animated PNG: full color and alpha transparency.
Animated WebP / AVIF Much smaller than GIF for the same animation; supported by all current major browsers.
SVG Tiny, sharp at any size, animated with CSS or SMIL. Animation runs inside <img>, but scripts and links in the SVG do not.

For anything longer than a few seconds, a muted looping <video> is almost always smaller and smoother than an animated image (see Video).

An <img> has no pause button, so you are responsible for motion that starts on its own. Movement can make people with vestibular disorders feel ill, and WCAG asks for a way to pause anything that moves for more than five seconds. Respect the user's system setting with the prefers-reduced-motion media query. The demo below spins an SVG; if your operating system has "reduce motion" turned on, it stays still.

An animation that respects reduced motion

To serve a still image to those users, put a <source media="(prefers-reduced-motion: reduce)"> with a static file inside a <picture> (see Responsive Images).

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. A small leaf icon sits right next to the word "Eco-friendly". What alt text should the icon have?

    The icon repeats what the text already says, so it is decorative. An empty alt makes screen readers skip it. Leaving alt out entirely may make them read the file name.
  2. 2. Why should you set width and height on an image when CSS makes it responsive anyway?

    With width, height and height: auto in CSS, the browser knows the image's shape before the file arrives and holds the right amount of space for it.
  3. 3. Which image should NOT use loading="lazy"?

    The hero image is visible immediately and is often the most important content. Lazy-loading it delays it for no benefit.
  4. 4. Which format is usually the best choice for a company logo?

    Logos are drawn shapes, so a vector SVG stays sharp at every size and is usually tiny.

Summary

  • <img> is a void element; src points to the file and alt provides the text alternative.
  • Write alt text that replaces the image's purpose. Use alt="" for decorative images, and never omit alt.
  • Set width and height to the real pixel size; with max-width: 100%; height: auto the image stays responsive without layout shift.
  • Use SVG for drawn graphics and WebP or AVIF for photos; JPEG and PNG remain safe fallbacks.
  • loading="lazy" defers off-screen images; keep the top-of-page image eager.
  • Align images with CSS (float, margin-inline: auto, flexbox), never the obsolete align attribute; an image that is the only content of a link needs alt text naming the destination.
  • Animated GIF, APNG, WebP and SVG all work in <img>; honor prefers-reduced-motion for motion that starts on its own.

Next up: serving the right image to every screen with Responsive Images.