HTML5 Mastery: The Complete Web Foundation
HomeInsightsCoursesHTMLImage Tag & Attributes
Images & Graphics

Images & Image Tags

Master the img element and display images on the web. Learn about image formats, alt text, responsive images, and optimization techniques for better performance.

The <img> Element

The <img> element embeds images into web pages. It's a self-closing (void) element that requires the src attribute.

Basic Image Syntax
HTML
<img src="path/to/image.jpg" alt="Description of image">

Required Attributes:

  • src - Source URL of the image (required)
  • alt - Alternative text description (required for accessibility)

Essential Image Attributes

1. src (Source)

Specifies the path to the image file:

HTML
<!-- Relative path --&gt;
<img src="images/photo.jpg" alt="Photo">

<!-- Root-relative path --&gt;
<img src="/assets/images/logo.png" alt="Logo">

<!-- Absolute URL --&gt;
<img src="https://example.com/images/banner.jpg" alt="Banner">

<!-- Data URL (base64 encoded) --&gt;
<img src="data:image/png;base64,iVBORw0KGg..." alt="Inline image">

2. alt (Alternative Text)

Critical for accessibility and SEO:

HTML
<!-- Descriptive alt text --&gt;
<img src="golden-retriever.jpg" alt="Golden retriever playing fetch in park">

<!-- Decorative image (empty alt) --&gt;
<img src="decorative-divider.png" alt="">

<!-- Logo --&gt;
<img src="company-logo.png" alt="Acme Corporation">

<!-- Icon with context --&gt;
<img src="checkmark.svg" alt="Success">

Writing Good Alt Text:

✅ Do

  • Be descriptive and specific
  • Keep it concise (under 125 characters)
  • Describe content, not "image of" or "picture of"
  • Use empty alt="" for decorative images
  • Include text in image if relevant
  • Provide context for function/purpose

❌ Don't

  • Leave alt attribute out entirely
  • Use "image" or "photo" in description
  • Be vague ("dog" vs "golden retriever")
  • Write essays (keep it brief)
  • Include "image of" or "picture of"
  • Use filename as alt text

3. width and height

Specify image dimensions to prevent layout shift:

HTML
<!-- Explicit dimensions --&gt;
<img src="photo.jpg" alt="Photo" width="800" height="600">

<!-- Aspect ratio preserved --&gt;
<img src="photo.jpg" alt="Photo" width="400" height="300">

<!-- In CSS (preferred for responsive) --&gt;
<img src="photo.jpg" alt="Photo" style="width: 100%; height: auto;">
💡
Why Specify Dimensions:
  • Prevents layout shift as page loads (better CLS score)
  • Browser reserves space before image loads
  • Improves user experience
  • Better Core Web Vitals scores

4. loading (Lazy Loading)

Defer loading images until needed:

HTML
<!-- Load immediately (default) --&gt;
<img src="hero.jpg" alt="Hero" loading="eager">

<!-- Lazy load (below fold) --&gt;
<img src="photo1.jpg" alt="Photo" loading="lazy">
<img src="photo2.jpg" alt="Photo" loading="lazy">
<img src="photo3.jpg" alt="Photo" loading="lazy">
ValueWhen to UseBehavior
eagerAbove-the-fold imagesLoad immediately (default)
lazyBelow-the-fold imagesLoad when near viewport

5. title (Tooltip)

Shows on hover (use sparingly):

HTML
<img src="icon.png" alt="Help" title="Click for more information">
⚠️ Don't rely on title: Many users won't see tooltips (mobile, keyboard users, screen readers). Use alt text for important information.

Image Formats

Choose the right format for your needs:

📸 JPEG (.jpg, .jpeg)

  • Best for: Photographs, complex images
  • Pros: Small file sizes, good compression
  • Cons: Lossy compression, no transparency
  • Use when: Photos with many colors

🎨 PNG (.png)

  • Best for: Graphics, logos, icons
  • Pros: Lossless, supports transparency
  • Cons: Larger file sizes than JPEG
  • Use when: Need transparency or sharp edges

🚀 WebP (.webp)

  • Best for: Modern web (all purposes)
  • Pros: Best compression, transparency support
  • Cons: Limited older browser support
  • Use when: Targeting modern browsers

🎭 SVG (.svg)

  • Best for: Icons, logos, illustrations
  • Pros: Scalable, small file size, crisp at any size
  • Cons: Not suitable for photos
  • Use when: Vector graphics, need scaling

🎬 GIF (.gif)

  • Best for: Simple animations
  • Pros: Supports animation, wide support
  • Cons: Limited colors (256), large files
  • Use when: Simple animations (prefer video)

🆕 AVIF (.avif)

  • Best for: Next-gen compression
  • Pros: Best compression, high quality
  • Cons: New format, limited support
  • Use when: Progressive enhancement

Responsive Images

Serve different image sizes based on screen size and resolution:

CSS-Only Responsive Images

HTML
<img src="photo.jpg" alt="Photo" style="max-width: 100%; height: auto;">

<style>
img {
    max-width: 100%;
    height: auto;
}
</style>

Using srcset (Resolution Switching)

Serve different resolutions for different pixel densities:

HTML
<img 
    src="image-800w.jpg" 
    srcset="image-400w.jpg 400w,
            image-800w.jpg 800w,
            image-1200w.jpg 1200w"
    sizes="(max-width: 600px) 400px,
           (max-width: 1000px) 800px,
           1200px"
    alt="Responsive image"
>

How srcset Works:

  1. srcset lists available image files with their widths
  2. sizes tells browser what size the image will be displayed at
  3. Browser chooses best image based on viewport size and pixel density
  4. src is fallback for older browsers

Using <picture> Element (Art Direction)

Serve completely different images for different contexts:

HTML
<picture>
    <!-- Mobile: Portrait crop --&gt;
    <source media="(max-width: 600px)" srcset="image-mobile.jpg">
    
    <!-- Tablet: Square crop --&gt;
    <source media="(max-width: 1000px)" srcset="image-tablet.jpg">
    
    <!-- Desktop: Landscape crop --&gt;
    <source media="(min-width: 1001px)" srcset="image-desktop.jpg">
    
    <!-- Fallback --&gt;
    <img src="image-desktop.jpg" alt="Responsive image">
</picture>

Modern Format Fallbacks

HTML
<picture>
    <!-- Try AVIF (best compression) --&gt;
    <source type="image/avif" srcset="image.avif">
    
    <!-- Try WebP (good compression) --&gt;
    <source type="image/webp" srcset="image.webp">
    
    <!-- Fallback to JPEG (universal support) --&gt;
    <img src="image.jpg" alt="Image">
</picture>

Image Optimization

✅ Optimization Checklist:

  • ☑ Choose right format: JPEG for photos, PNG for graphics, WebP for modern web
  • ☑ Compress images: Use tools like TinyPNG, ImageOptim, Squoosh
  • ☑ Serve correctly sized images: Don't serve 4000px image for 400px display
  • ☑ Use lazy loading: Add loading="lazy" for below-fold images
  • ☑ Specify dimensions: Always include width and height
  • ☑ Use CDN: Serve images from CDN for faster delivery
  • ☑ Enable caching: Set proper cache headers
  • ☑ Use responsive images: Implement srcset for multiple sizes
Optimized Image Example
HTML
<picture>
    <!-- WebP for modern browsers --&gt;
    <source 
        type="image/webp" 
        srcset="photo-400.webp 400w,
                photo-800.webp 800w,
                photo-1200.webp 1200w"
        sizes="(max-width: 600px) 400px,
               (max-width: 1000px) 800px,
               1200px"
    >
    
    <!-- JPEG fallback --&gt;
    <img 
        src="photo-800.jpg"
        srcset="photo-400.jpg 400w,
                photo-800.jpg 800w,
                photo-1200.jpg 1200w"
        sizes="(max-width: 600px) 400px,
               (max-width: 1000px) 800px,
               1200px"
        alt="Beautiful landscape"
        width="1200"
        height="800"
        loading="lazy"
    >
</picture>

Styling Images with CSS

Common Image Styles
CSS
/* Basic responsive */
img {
    max-width: 100%;
    height: auto;
}

/* Rounded corners */
img.rounded {
    border-radius: 10px;
}

/* Circle (for avatars) */
img.circle {
    border-radius: 50%;
    width: 100px;
    height: 100px;
    object-fit: cover;
}

/* Shadow */
img.shadow {
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

/* Grayscale filter */
img.grayscale {
    filter: grayscale(100%);
}

img.grayscale:hover {
    filter: grayscale(0%);
    transition: filter 0.3s;
}

/* Object-fit (like background-size) */
img.cover {
    width: 100%;
    height: 300px;
    object-fit: cover; /* Fill container, crop if needed */
}

img.contain {
    width: 100%;
    height: 300px;
    object-fit: contain; /* Fit inside, show all */
}

/* Border */
img.framed {
    border: 5px solid white;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
}

Figure and Figcaption

Semantic way to associate images with captions:

HTML
<figure>
    <img src="photo.jpg" alt="Mountain landscape">
    <figcaption>Rocky Mountains at sunset, Colorado</figcaption>
</figure>

<style>
figure {
    margin: 2rem 0;
    text-align: center;
}

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

figcaption {
    margin-top: 0.5rem;
    font-size: 0.9rem;
    color: #666;
    font-style: italic;
}
</style>

Decorative vs. Meaningful Images

Meaningful Images

Convey information or content:

HTML
<!-- Product photo --&gt;
<img src="laptop.jpg" alt="15-inch MacBook Pro">

<!-- Infographic --&gt;
<img src="chart.png" alt="Sales increased 45% in Q4">

<!-- Tutorial screenshot --&gt;
<img src="step1.png" alt="Click the File menu">

Decorative Images

Purely visual, no information:

HTML
<!-- Decorative border --&gt;
<img src="divider.png" alt="">

<!-- Background pattern --&gt;
<img src="pattern.png" alt="">

<!-- Decorative icon (when text explains) --&gt;
<img src="icon.svg" alt="">
<p>Download our app</p>
💡 Rule of Thumb: If removing the image would lose information, it's meaningful (needs descriptive alt text). If it's just for decoration, use empty alt="".

Common Image Mistakes

❌ Missing Alt Text

HTML
<img src="photo.jpg">  <!-- Wrong! --&gt;
HTML
<img src="photo.jpg" alt="Description">  <!-- Correct --&gt;

❌ Using Image for Text

HTML
<img src="heading.png" alt="Welcome">  <!-- Bad for SEO/accessibility --&gt;
HTML
<h1>Welcome</h1>  <!-- Use real text --&gt;

❌ Huge Unoptimized Images

HTML
<!-- 5MB image for 300px display --&gt;
<img src="photo-4000x3000.jpg" width="300">
HTML
<!-- Properly sized and compressed --&gt;
<img src="photo-600x450.jpg" width="300" loading="lazy">

❌ Not Specifying Dimensions

HTML
<img src="photo.jpg" alt="Photo">  <!-- Causes layout shift --&gt;
HTML
<img src="photo.jpg" alt="Photo" width="800" height="600">  <!-- Better --&gt;

Best Practices Summary

✅ Do

  • Always include alt text
  • Optimize images before uploading
  • Specify width and height
  • Use lazy loading for below-fold images
  • Choose appropriate file format
  • Implement responsive images
  • Use modern formats with fallbacks
  • Test images on slow connections

❌ Don't

  • Forget alt attributes
  • Serve oversized images
  • Use images for text content
  • Ignore mobile optimization
  • Use poor quality images
  • Forget about loading performance
  • Use spacer.gif (deprecated)
  • Hotlink images from other sites

What's Next?

Now that you understand images, let's explore the picture element and art direction in depth.