Skip to main content
← πŸ“„ HTML & the platformΒ·Module A4 Β· Lesson 5
TaskAdd an image with src='/hero.jpg', alt='Three developers at a whiteboard', width='1200', height='630', loading='lazy'.

<img>: alt, width/height, lazy loading

100 XP8 min
Theory

The four attributes that matter

<img src="/hero.jpg"
     alt="Aerial view of San Francisco at sunset"
     width="1200" height="630"
     loading="lazy"
     decoding="async" />
  • `alt` β€” what the image SHOWS. For decoration only, use alt="" (empty alt β€” screen readers skip it). NEVER omit the attribute entirely.
  • `width` + `height` β€” intrinsic pixel dimensions. The browser reserves the space BEFORE downloading, preventing CLS (Cumulative Layout Shift). Lighthouse penalizes images without dimensions hard.
  • `loading="lazy"` β€” defer download until the image is near the viewport. Big win for long pages. Set on every image below the fold.
  • `decoding="async"` β€” decode off the main thread.

alt-text mini-lesson

ImageGood altBad alt
Hero photo"Three developers at a whiteboard""image" or "hero"
Logo"CodeMentor AI""Logo"
Decorative patternalt="""decorative pattern"
Chart"Revenue grew 40% in Q3""Bar chart"
Icon next to text "Settings"alt="" (text already says it)"Settings icon"

Width/height vs aspect-ratio CSS

Specify width AND height in the attributes. Modern browsers compute the aspect ratio from them and reserve correct space even when CSS makes the image fluid (max-width: 100%; height: auto). The "always set width and height" rule applies.

πŸ”’

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β€” card required, cancel anytime.

Sign up β€” free trial β†’

First 10 lessons in each track are free. No card needed for those.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.