🌱BeginnerImages and Media

Images

Embed images with <img>, understand src and alt attributes, and control size.

Overview

The <img> element embeds images into a web page. It is a void element no closing tag because it has no content; it simply references an external image file. The two required attributes are: - src: the path or URL to the image file - alt: alternative text describing the image Alt text is critical for accessibility (screen readers read it aloud) and appears when the image fails to load. It also helps search engines understand image content. HTML supports common formats: JPEG/JPG (photos), PNG (transparency), GIF (animation), WebP (modern, smaller), and SVG (scalable vectors).

Key Points

  • •<img> is a void element it has no closing tag
  • •src specifies the image source: a URL or file path
  • •alt text is required for accessibility describe what the image shows
  • •Use alt="" for decorative images that a screen reader should skip
  • •width and height attributes prevent layout shifts while images load
  • •Prefer WebP format for smaller file sizes; use JPEG for photos, PNG for transparency

Examples

Basic image with required attributes

<img src="photo.jpg" alt="A golden retriever puppy sitting on grass">

Always write descriptive alt text. "Dog" is bad; the description above is good.

Image with width and height to prevent layout shift

<img
  src="banner.jpg"
  alt="Welcome banner for our website"
  width="800"
  height="300"
>

Specifying width and height lets the browser reserve space before the image loads.

Decorative image with empty alt

<!-- Purely decorative screen readers skip it -->
<img src="divider-line.png" alt="">

Image inside a link

<a href="/gallery">
  <img src="thumbnail.jpg" alt="View our photo gallery">
</a>

When an image is inside a link, the alt text should describe the link's destination.

Responsive images with CSS

<style>
  img { max-width: 100%; height: auto; }
</style>
<img src="hero.jpg" alt="Mountain landscape at sunset">

This CSS pattern makes images scale down on smaller screens without distortion.

Common Mistakes

  • Omitting the alt attribute required by HTML spec and accessibility guidelines
  • Writing useless alt text like "image" or repeating the filename
  • Not specifying width/height causes Cumulative Layout Shift (CLS) affecting performance scores

Note

Write alt text as if describing the image to someone on a phone call. Be specific but concise. If the image is decorative, use alt="" to tell screen readers to skip it.

Exercises

Write HTML to solve each exercise. Use Preview to see it render in a live iframe, then mark as done.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What does the alt attribute on <img> do?