HTML Basics
Images
Master image elements (img) in HTML, covering src paths, accessibility alt descriptions, native lazy loading, and layout shift (CLS) prevention.
1. Learning Objectives
In this lesson, you will master the implementation of images. By the end of this topic, you will be able to:
- Embed images using the void
<img>element. - Write descriptive, compliant
alttext to maximize accessibility. - Set explicit sizing attributes (
widthandheight) to prevent Cumulative Layout Shift (CLS). - Leverage native browser lazy loading (
loading="lazy") to optimize page load speeds. - Use semantic figure wrappers (
<figure>and<figcaption>).
2. Overview
Images are embedded in HTML documents using the self-closing (void) <img> element. It does not wrap text content, instead pulling file paths using the src attribute. Additional attributes govern layout dimensions, descriptive fallbacks, and fetch prioritization.
3. Why This Topic Matters
Images make up a major percentage of web page file sizes. Misconfiguring image elements leads to bad performance:
- Cumulative Layout Shift (CLS): If you do not specify image dimensions, the browser cannot allocate layout space before downloading the image file. Once the image loads, page elements jump down suddenly, disrupting the user experience.
- SEO and Screen Reader Failures: Visually impaired users relying on screen readers hear only the filename (e.g. "IMG_88291.jpg") if the
alttag is missing.
4. Real-World Analogy
Think of an HTML image tag like **hanging a framed painting on a wall**:
- The Picture Frame (Explicit width/height): You mark an exact outline on the wall where the painting will hang. Guests won't bump into furniture because the layout is already fixed.
- The Label (Alt Text): A description card placed next to the frame explaining what the painting depicts for visually impaired museum visitors.
- Delivery on Demand (Lazy Loading): Storing paintings in the warehouse and only hanging them on the wall when a visitor approaches that specific room corridor.
5. Core Concepts
| Attribute | Core Purpose | Format Requirements |
|---|---|---|
| src | Declares the local path or absolute URL of the image asset. | String file path or URL coordinate. |
| alt | Provides alternative text descriptions for SEO crawlers and screen readers. | Descriptive phrase (avoid words like "image of"). |
| loading | Configures whether the browser should defer loading images until they are near the viewport. | lazy or eager (default) |
6. Syntax & API Reference
Images are self-closing void elements. Declared dimensions inside HTML must be unitless numbers (representing pixels):
Semantic Wrapping (Figure Elements):
To group images with captions, wrap them in a <figure> element:
7. Visual Diagram
This diagram displays how the browser uses explicit sizing attributes to allocate space and prevent page reflows:
8. Live Example — Full Working Code
A sample HTML file showing semantic figure nesting and lazy loading:
9. Interactive Playground
Try It Yourself Challenges:
- Change the
loadingattribute toeagerand review network priority changes in your browser's DevTools Network tab. - Test what happens if you input a broken path inside
src. Confirm how thealtdescription displays.
10. Common Mistakes
| Mistake | Why it happens | Wrong | Correct |
|---|---|---|---|
| Missing alt tags | Forgetting alt text, leaving screen readers to read raw filenames. | <img src="banner.jpg"> |
<img src="banner.jpg" alt="Summer sales campaign banner"> |
| Adding units to HTML sizes | Declaring pixel units inside HTML width/height attributes. | width="500px" |
width="500" |
11. Best Practices
- Always specify dimensions: Set explicit unitless `width` and `height` attributes on HTML image tags. This allows the browser to calculate the aspect ratio and reserve layout space, preventing layout shifts.
- Keep alt text descriptive and concise: Describe the content of the image. Avoid starting with phrases like "image of..." or "photo of..." since screen readers already announce the element as an image.
- Use empty alt tags for decorative elements: If an image is purely decorative (like a divider line or decorative shape), use
alt="". This tells screen readers to skip the element entirely. - Lazy load off-screen images: Set
loading="lazy"for images located below the fold to reduce initial page load times and save bandwidth. Do not lazy load the primary hero image at the top of the page.
12. Browser Compatibility
| Feature | Chrome | Firefox | Safari | Edge |
|---|---|---|---|---|
| loading="lazy" support | Supported (77+) | Supported (75+) | Supported (15.4+) | Supported (79+) |
13. Interview Questions
🟢 Q1: How do explicit width and height attributes prevent Cumulative Layout Shift (CLS)?
Answer: When the HTML parser runs into an <img> tag with explicit dimensions, it uses the width and height to calculate the aspect ratio before downloading the asset. The browser reserves a placeholder box in the layout flow, allowing surrounding text to render in its final position. If dimensions are missing, the placeholder has a height of 0px, causing the page elements to jump down suddenly once the image downloads.
14. Debugging Exercise
Find the performance and syntax issues in this image implementation:
Fixed code:
15. Practice Exercises
Exercise 1: Profile Card Layout
Build a simple profile card markup structure containing a user avatar photo, wrapped inside a semantic figure tag, with a corresponding figcaption showing the team member's role and email link.
16. Scenario-Based Challenge
The Mobile Page Performance Speed Challenge:
A mobile commerce catalog contains 150 product detail items on a single long scrolling page. The page loads slowly on slow mobile networks because the browser tries to download all 150 product photos simultaneously. Outline how implementing lazy loading resolves this performance bottleneck.
17. Quick Quiz
Q1: Which attribute should be used to describe the content of an image for accessibility?
A) src
B) alt
C) desc
Answer: B — The alt attribute provides alternative description text for image tags.
18. Summary & Key Takeaways
- • Specify unitless dimensions to block layout shifts.
- • Write alt description text to pass basic web accessibility checks.
19. Cheat Sheet
| Attribute / Element | Key Purpose |
|---|---|
loading="lazy" |
Defers downloading images until they approach the viewport boundaries. |