Skip to main content

πŸ–ΌοΈ Image Integration and Attributes

Images carry a huge share of the meaning β€” and the weight β€” of a web page. This lesson shows you how to embed them correctly with the <img> element, pick the right file format, serve the right size to every device, and write alt text that makes your content work for everyone.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Embed images with the <img> element and its essential src and alt attributes
  • Choose the right image format (JPEG, PNG, SVG, WebP, AVIF) for each use case
  • Prevent layout shift with width/height and speed pages up with loading="lazy"
  • Serve responsive images with srcset, sizes, and the <picture> element
  • Write effective alt text and use <figure>/<figcaption> for captions

Estimated Time: 30–40 minutes  β€’  Difficulty: Beginner

Hands-on: Build a responsive, accessible image card with a caption and a lazy-loaded source set.

In This Lesson

Why Images Need Care

A well-chosen image can explain in a glance what a paragraph struggles to say. But images are also, by far, the heaviest thing most pages download β€” often more bytes than all the HTML, CSS, and JavaScript combined. Get them wrong and your page is slow, inaccessible, and jumps around as it loads. Get them right and it's fast, inclusive, and beautiful.

Everything in HTML images comes down to three questions: What are you showing (which format)? How big should it be on each device (responsive sizing)? And what does it mean to someone who can't see it (alt text)? This lesson answers all three.

graph TD A[Adding an image] --> B[Integration: img, src, alt] A --> C[Format: JPEG / PNG / SVG / WebP / AVIF] A --> D[Responsiveness: srcset / sizes / picture] A --> E[Accessibility: alt / figure / figcaption] A --> F[Performance: width+height / lazy loading]

The img Element

At minimum, an image needs two attributes: src (where the file is) and alt (what it shows). The <img> element is a void element β€” it has no closing tag.

<img src="/images/puppy.jpg" alt="A golden retriever puppy playing with a red ball">
Anatomy of an img element A diagram showing an image placeholder next to the img tag, with the src attribute labelled as the file path and alt as the accessible description. [ image ] <img src="/images/puppy.jpg" alt="A golden puppy…"> path to the file accessible description
Figure 1 β€” The src points to the image file; the alt describes it for screen readers, search engines, and anyone whose image fails to load.

The src can be a root-relative path (/images/logo.png), a relative path (images/logo.png), or a full URL to a remote host. As with links, root-relative paths are the most robust for multi-folder sites.

πŸ“– Why alt text matters

The alt attribute is read aloud by screen readers, shown when an image fails to load, indexed by search engines, and used by browsers to reserve meaning before pixels arrive. It is the single most important attribute after src β€” never leave it off a meaningful image.

Choosing an Image Format

Each format is a trade-off between quality, file size, transparency, and browser support. Matching the format to the content is the biggest single win for image performance.

FormatBest forTransparencyNotes
JPEGPhotographsNoSmall files, lossy compression, millions of colours
PNGGraphics, screenshots, textYesLossless, larger than JPEG
SVGLogos, icons, diagramsYesVector β€” infinitely scalable, tiny, editable as code
WebPPhotos & graphics (modern)Yes~25–35% smaller than JPEG/PNG; supported everywhere today
AVIFNext-gen photosYesBest compression; broad but not universal support

Here's a quick decision path:

graph TD A{What is the image?} --> B[Photograph] A --> C[Logo or icon] A --> D[Graphic with transparency] B --> E[Prefer WebP or AVIF, fall back to JPEG] C --> F[Use SVG when possible] D --> G[WebP, fall back to PNG]

βœ… Modern default

For 2026, reach for WebP as your everyday photo and graphic format, offer AVIF to browsers that support it via <picture>, keep a JPEG/PNG fallback, and use SVG for anything vector.

Performance Attributes

width and height β€” stop the page from jumping

Always set width and height to the image's real pixel dimensions, even when CSS resizes it. The browser uses that ratio to reserve space before the image downloads, preventing Cumulative Layout Shift (CLS) β€” the annoying jump where content leaps down as an image pops in.

<img src="/images/banner.jpg" alt="Summer sale banner" width="1200" height="600">

Pair this with a little CSS so the image stays responsive while keeping its aspect ratio:

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

loading β€” defer off-screen images

Add loading="lazy" to images below the fold so the browser waits until they're about to scroll into view. This can dramatically cut the initial page weight.

<img src="/images/footer-photo.jpg" alt="Our office building" width="800" height="533" loading="lazy">

Do not lazy-load your most important above-the-fold image (like a hero) β€” that would delay the thing users came to see. For that image, use fetchpriority="high" instead.

decoding β€” keep the main thread free

decoding="async" hints that the browser may decode the image off the main thread, keeping the page responsive.

<img src="/images/profile.webp" alt="Jane Smith, Marketing Director"
     width="200" height="200" decoding="async">

πŸ’‘ The performance trio

For a typical content image below the fold: set width + height, add loading="lazy", and add decoding="async". Three small attributes, measurably faster pages.

Responsive Images

A phone on a slow network should not download the same 2000-pixel-wide image as a 4K desktop. Responsive-image markup lets the browser pick the best file for the screen and connection.

srcset + sizes β€” same image, many resolutions

List several widths of the same picture in srcset (each tagged with its real pixel width using the w descriptor), and describe the display width with sizes. The browser does the math and downloads just one file.

<img
  src="/images/photo-800.jpg"
  srcset="/images/photo-400.jpg 400w,
          /images/photo-800.jpg 800w,
          /images/photo-1200.jpg 1200w"
  sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 33vw"
  alt="A quiet forest path in autumn"
  width="800" height="533">

The src is the fallback for very old browsers. The sizes value reads: "up to 600px wide, the image fills the viewport; up to 1200px it takes half; otherwise a third."

The picture element β€” different images or formats

Use <picture> when you need to swap the actual image (art direction) or offer modern formats with a fallback. The browser picks the first matching <source>; the <img> is the required last resort.

<!-- Offer AVIF, then WebP, then JPEG -->
<picture>
  <source type="image/avif" srcset="/images/hero.avif">
  <source type="image/webp" srcset="/images/hero.webp">
  <img src="/images/hero.jpg" alt="Mountains at sunrise" width="1200" height="800">
</picture>

<!-- Art direction: a tall crop on phones, wide on desktop -->
<picture>
  <source media="(max-width: 600px)" srcset="/images/portrait.jpg">
  <img src="/images/landscape.jpg" alt="Team celebrating a launch" width="1200" height="675">
</picture>

⚠️ Always include the img

A <picture> with no <img> shows nothing. The <img> is what actually renders β€” and it's where the alt, width, and height live.

Alt Text & Accessibility

Good alt text describes the content and function of an image concisely β€” usually under ~125 characters. Skip "image of…" (screen readers already announce it as an image), and use an empty alt="" for purely decorative images so they're silently skipped.

ContextPoor altGood alt
Company logo"logo""Acme Corporation"
Product photo"bag""Red leather crossbody bag with gold clasp"
Sales chart"chart""Bar chart: sales up 15% year over year, 2024–2026"
Decorative divider"divider"alt="" (empty)

figure and figcaption

When an image needs a visible caption, wrap it in <figure> with a <figcaption>. The caption and the alt text serve different audiences, so you still write both β€” alt for those who can't see the image, the caption for everyone.

<figure>
  <img src="/images/traffic.webp"
       alt="Line chart of monthly visitors rising from 5k in January to 20k in June"
       width="800" height="450">
  <figcaption>Figure 4 β€” Monthly site traffic, Jan–Jun 2026. Source: Analytics.</figcaption>
</figure>

πŸ’‘ Decorative vs. meaningful

Ask: "If this image vanished, would the user miss information?" If yes, it needs descriptive alt text. If it's pure decoration, give it alt="" so assistive tech ignores it β€” never omit the attribute entirely, which makes some screen readers read the filename aloud.

Hands-on Exercise

πŸ‹οΈ Build a Responsive Image Card

Objective: Combine formats, responsive sizing, lazy loading, and a caption into one accessible card.

Instructions:

  1. Create a <figure> containing one image and a <figcaption>.
  2. Give the image a srcset with at least two widths and a matching sizes value.
  3. Set explicit width and height and add loading="lazy".
  4. Write descriptive alt text that would make sense if the image never loaded.
  5. Add CSS so the image is max-width: 100%; height: auto; and fills its card.
πŸ’‘ Hint

Each srcset entry is path width_descriptor, e.g. photo-400.jpg 400w. The sizes value tells the browser how wide the image renders at each breakpoint, so it can pick the smallest file that still looks sharp.

βœ… Sample solution
<figure class="image-card">
  <img
    src="/images/mountain-800.jpg"
    srcset="/images/mountain-400.jpg 400w,
            /images/mountain-800.jpg 800w,
            /images/mountain-1200.jpg 1200w"
    sizes="(max-width: 700px) 100vw, 400px"
    alt="Snow-capped mountain peak under a clear blue sky"
    width="800" height="533"
    loading="lazy" decoding="async">
  <figcaption>Mount Rainier at dawn.</figcaption>
</figure>
.image-card { max-width: 400px; border-radius: 8px; overflow: hidden; }
.image-card img { width: 100%; height: auto; display: block; }

Best Practices

βœ… Do

  • Always provide descriptive alt text for meaningful images and alt="" for decorative ones.
  • Set width and height on every image to prevent layout shift.
  • Use modern formats (WebP/AVIF) with a fallback, and SVG for logos and icons.
  • Serve responsive sizes with srcset/sizes and lazy-load below-the-fold images.
  • Use descriptive filenames (red-leather-bag.jpg, not IMG_0042.jpg).

⚠️ Avoid

  • Serving one giant image and shrinking it with CSS β€” the phone still downloads every byte.
  • Omitting the alt attribute entirely (empty is fine; missing is not).
  • Lazy-loading the hero image β€” it delays your most important content.
  • Starting alt text with "image of" or stuffing it with keywords.

Summary & Quiz

πŸŽ‰ Key Takeaways

  • The <img> element needs src and alt; alt text serves accessibility, SEO, and failed loads.
  • Match the format to the content: WebP/AVIF for photos, SVG for vectors, PNG for transparency.
  • Set width + height to stop layout shift; add loading="lazy" below the fold.
  • srcset/sizes serve the right resolution; <picture> swaps formats or art direction.
  • Use <figure>/<figcaption> for captions β€” and still write alt text.

🎯 Quick Quiz

Question 1: Why should you set explicit width and height on an image?

Question 2: Which element would you use to offer an AVIF image with a JPEG fallback?

Question 3: What is the correct alt value for a purely decorative divider image?

πŸ“š Further Reading

πŸš€ What's Next?

You can now add images that are fast, responsive, and accessible. Next we go beyond still pictures into motion and sound: audio and video implementation with HTML5's native media elements.

πŸŽ‰ Well done!

Your pages can now show the right image, at the right size, described the right way β€” for every visitor.