HTML Tutorial 0/139 lessons ~6 min read Lesson 16

    HTML Images

    html images images tie together accessibility, seo image search, and core web vitals. staff the img element embeds raster

    Course progress0%
    Focus
    18 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    The img element embeds raster (and SVG via img) content with alt text for accessibility and SEO. LCP element on most PDPs is an image — Amazon, Shopify, and Airbnb invest heavily in srcset, dimensions, and CDN URLs in HTML. Staff engineers never ship decorative images with missing alt or product images with empty alt.

    Business problem

    Image markup errors directly hit revenue: missing dimensions cause CLS penalties, blank alt on product photos hides listings from image search, oversized src hurts mobile LCP and data caps.

    • SEO: Google Image Search drives 20%+ traffic on recipe and ecommerce verticals — alt and structured filenames matter.
    • Legal: WCAG lawsuits cite product galleries with alt="image" or duplicated boilerplate.
    • Perf: 4MB hero on src without srcset — bounce rate doubles on 3G.

    Why this feature exists

    Early web was hypertext plus documents — img from Mosaic era. Replaced inline images in proprietary formats. Responsive images (srcset, sizes) added in HTML5 without breaking single-src legacy.

    • History: ismap deprecated; usemap rare; picture element for art direction.
    • Rejected: Embedding binary inline in HTML — base64 bloats TTFB.
    • Modern: loading=lazy, fetchpriority=high, decoding=async — HTML hooks for scheduler.

    Browser internals

    HTMLImageElement triggers resource fetch when src/srcset parsed. Dimensions width/height set intrinsic size before decode — prevents layout shift. Decode async vs sync affects when pixels appear; lazy images defer until intersection.

    • Responsive selection: Browser picks descriptor from srcset + sizes + DPR.
    • CORS: crossorigin attribute required for canvas read of CDN images.
    • Error: onerror event — fallback src pattern common on avatars.
    text
    <img srcset="400w 400w, 800w 800w" sizes="(max-width:600px) 100vw, 400px"
    width="400" height="300" alt="…" loading="lazy" decoding="async">
    → pick resource → fetch → decode → paint

    Rendering workflow

    Images are replaced elements — separate layer often composited. LCP candidate discovered at parse time if not lazy. fetchpriority=high on hero tells browser scheduler priority over lazy below-fold thumbs.

    • LCP: Hero img in HTML not JS — discoverable in first chunk.
    • CLS: width/height or aspect-ratio CSS — mandatory on CMS templates.
    • Lazy: Never lazy above-fold LCP image — kills priority.

    Feature deep dive

    Every img needs alt — empty alt="" only if decorative and adjacent text covers content. Use picture for WebP/AVIF fallbacks; srcset for resolution switching. Prefer CDN with automatic format negotiation documented in HTML comments stripped at build.

    • Product: Alt describes product, not "photo" — "Red Nike Air Max size 10 side view".
    • Decorative: alt="" role=presentation optional — don't omit alt attribute.
    • SVG: img for decorative; inline SVG for icon with title/desc if informative.
    html
    <picture>
    <source type="image/avif" srcset="/hero.avif">
    <source type="image/webp" srcset="/hero.webp">
    <img src="/hero.jpg" alt="Host welcome guests on a sunny patio"
    width="1200" height="630" fetchpriority="high">
    </picture>

    Accessibility analysis

    Alt is the text alternative — screen readers announce it; no alt means filename or "image" read aloud. Complex charts need longdesc replacement via aria-describedby linking to data table. BBC requires alt approval in editorial workflow.

    • Redundant: Don't start alt with "Image of" — AT already says graphic.
    • Linked images: Alt describes destination if image is sole link content.
    • WCAG: 1.1.1 Non-text Content — functional images need action description.

    SEO impact

    Google Images uses alt, surrounding text, and file context. Product structured data pairs with primary image URL. Lazy images still indexed if in DOM at crawl — but LCP image should not be hidden behind JS gallery init.

    • Filename: Descriptive paths help — /images/red-running-shoe.jpg not IMG_8832.jpg.
    • Sitemaps: image:image namespace for discovery.
    • CLS: Core Web Vitals affect ranking — dimensions in HTML are SEO tech debt payoff.

    Security considerations

    User-uploaded images can be polyglot files — serve from separate domain, scan, Content-Type sniffing protection. SVG in img safer than inline script SVG. Referrer on hotlinked images leaks paths — use referrerpolicy on sensitive pages.

    • XSS: onerror="alert(1)" if inline handler allowed — CSP script-src blocks.
    • Tracking pixels: 1x1 img emails — privacy disclosure.
    • SSRF: Server fetching remote img URL from user input — block internal IPs.

    Performance impact

    Shopify CDN images append width params in Liquid — HTML emits right size per breakpoint. Amazon uses responsive grid with strict byte budgets per slot. Preload LCP image in head with imagesrcset/imagesizes match.

    • Formats: AVIF > WebP > JPEG — picture element in HTML.
    • Lazy: Native loading=lazy for below fold — no heavy JS library needed.
    • Priority: One fetchpriority=high per page — don't mark everything high.

    Real production example

    Airbnb listing gallery SSR first photo with dimensions and descriptive alt including location; subsequent thumbs lazy-loaded. RUM monitors LCP element — alert if not listing photo id pattern.

    • CMS validation: Block publish without alt on non-decorative flag.
    • CDN: Signed URLs expire — HTML cache TTL aligned.
    • Placeholder: LQIP blur in CSS — not alt text substitute.
    html
    <img
    src="https://cdn.example.com/listing/42.jpg?w=800"
    srcset="…480w 480w, …800w 800w, …1200w 1200w"
    sizes="(max-width: 768px) 100vw, 50vw"
    width="800" height="600"
    alt="Loft with Eiffel Tower view, Paris 7th arrondissement"
    loading="eager"
    fetchpriority="high">

    Enterprise usage

    Enterprise DAM integration pipes alt text from metadata — Google marketing CMS requires alt from licensed asset record. axe and custom lint fail PR without width/height on content images.

    • Legal: Rights-managed images — HTML data-rights-id for audit.
    • Email: Fixed width img — no srcset support in many clients.
    • Print: High-res src in media-specific picture source.

    Common production failures

    Retailer CLS regression when CMS removed width/height "for responsive CSS" — Search Console flagged URLs; took 6 weeks to recover rankings. Travel site alt="logo" on all property photos — image search traffic zero.

    • Lazy LCP: Developer added loading=lazy globally — LCP +2.5s.
    • Hotlink: CDN bill spike from missing referrer policy on public img URLs.
    • Broken src: Case-sensitive path on Linux CDN — 50% broken images post-migration.

    Architecture review questions

    • Does every img have appropriate alt — empty only when decorative?
    • Are width and height set to reserve space and prevent CLS?
    • Is the LCP image eager, high priority, and discoverable in initial HTML?
    • Does srcset/sizes match real layout breakpoints and CDN capabilities?
    • Are user-uploaded images served safely with correct CORS and scanning?
    • Is picture used for next-gen formats with JPEG fallback?

    Hands-on project

    Build a responsive product gallery with picture/srcset, LCP-first image policy, alt from product data, and Lighthouse LCP/CLS report before/after dimension fix.

    • Deliverable: Pass axe on alt; CLS < 0.1.
    • Verify: WebPageTest filmstrip shows early image paint.
    • Stretch: Preload hero with matching imagesizes.

    Interview questions

    How does the browser choose which srcset candidate to download?(Advanced)

    Uses sizes media query evaluation to get slot width, device pixel ratio, and srcset width descriptors (w) or density (x). Picks smallest adequate resource. Wrong sizes wastes bytes or picks too small blurry image.

    Follow-up: When use x descriptors vs w?

    LCP image best practices in HTML?(Advanced)

    In initial HTML, not lazy, fetchpriority=high, explicit dimensions, optimal format via picture, preload if discovered late due to lazy CSS background mistake. Avoid hiding in carousel without first slide in HTML.

    Follow-up: Background-image vs img for LCP?

    Alt text strategy for ecommerce with thousands of SKUs?(Advanced)

    Template from product attributes — color, brand, model, view angle. Human review for hero campaigns. Decorative badges alt="". Automate lint; manual spot audit. Don't keyword stuff — Google ignores spam alt.

    Follow-up: Same alt on gallery thumbnails?

    Try it yourself

    Edit the HTML, CSS, or JS panels — the preview updates as you type.

    Try it yourself

    Preview

    Summary

    Images tie together accessibility, SEO image search, and Core Web Vitals. Staff markup at Amazon and Airbnb standardizes alt from data, dimensions for CLS, and responsive srcset with explicit LCP priority in HTML.

    Ready to mark this lesson complete?Track your journey across the entire course.