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.
<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:
<!-- Relative path -->
<img src="images/photo.jpg" alt="Photo">
<!-- Root-relative path -->
<img src="/assets/images/logo.png" alt="Logo">
<!-- Absolute URL -->
<img src="https://example.com/images/banner.jpg" alt="Banner">
<!-- Data URL (base64 encoded) -->
<img src="data:image/png;base64,iVBORw0KGg..." alt="Inline image">2. alt (Alternative Text)
Critical for accessibility and SEO:
<!-- Descriptive alt text -->
<img src="golden-retriever.jpg" alt="Golden retriever playing fetch in park">
<!-- Decorative image (empty alt) -->
<img src="decorative-divider.png" alt="">
<!-- Logo -->
<img src="company-logo.png" alt="Acme Corporation">
<!-- Icon with context -->
<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:
<!-- Explicit dimensions -->
<img src="photo.jpg" alt="Photo" width="800" height="600">
<!-- Aspect ratio preserved -->
<img src="photo.jpg" alt="Photo" width="400" height="300">
<!-- In CSS (preferred for responsive) -->
<img src="photo.jpg" alt="Photo" style="width: 100%; height: auto;">- 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:
<!-- Load immediately (default) -->
<img src="hero.jpg" alt="Hero" loading="eager">
<!-- Lazy load (below fold) -->
<img src="photo1.jpg" alt="Photo" loading="lazy">
<img src="photo2.jpg" alt="Photo" loading="lazy">
<img src="photo3.jpg" alt="Photo" loading="lazy">| Value | When to Use | Behavior |
|---|---|---|
eager | Above-the-fold images | Load immediately (default) |
lazy | Below-the-fold images | Load when near viewport |
5. title (Tooltip)
Shows on hover (use sparingly):
<img src="icon.png" alt="Help" title="Click for more 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
<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:
<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:
srcsetlists available image files with their widthssizestells browser what size the image will be displayed at- Browser chooses best image based on viewport size and pixel density
srcis fallback for older browsers
Using <picture> Element (Art Direction)
Serve completely different images for different contexts:
<picture>
<!-- Mobile: Portrait crop -->
<source media="(max-width: 600px)" srcset="image-mobile.jpg">
<!-- Tablet: Square crop -->
<source media="(max-width: 1000px)" srcset="image-tablet.jpg">
<!-- Desktop: Landscape crop -->
<source media="(min-width: 1001px)" srcset="image-desktop.jpg">
<!-- Fallback -->
<img src="image-desktop.jpg" alt="Responsive image">
</picture>Modern Format Fallbacks
<picture>
<!-- Try AVIF (best compression) -->
<source type="image/avif" srcset="image.avif">
<!-- Try WebP (good compression) -->
<source type="image/webp" srcset="image.webp">
<!-- Fallback to JPEG (universal support) -->
<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
<picture>
<!-- WebP for modern browsers -->
<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 -->
<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
/* 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:
<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:
<!-- Product photo -->
<img src="laptop.jpg" alt="15-inch MacBook Pro">
<!-- Infographic -->
<img src="chart.png" alt="Sales increased 45% in Q4">
<!-- Tutorial screenshot -->
<img src="step1.png" alt="Click the File menu">Decorative Images
Purely visual, no information:
<!-- Decorative border -->
<img src="divider.png" alt="">
<!-- Background pattern -->
<img src="pattern.png" alt="">
<!-- Decorative icon (when text explains) -->
<img src="icon.svg" alt="">
<p>Download our app</p>Common Image Mistakes
⌠Missing Alt Text
<img src="photo.jpg"> <!-- Wrong! --><img src="photo.jpg" alt="Description"> <!-- Correct -->⌠Using Image for Text
<img src="heading.png" alt="Welcome"> <!-- Bad for SEO/accessibility --><h1>Welcome</h1> <!-- Use real text -->⌠Huge Unoptimized Images
<!-- 5MB image for 300px display -->
<img src="photo-4000x3000.jpg" width="300"><!-- Properly sized and compressed -->
<img src="photo-600x450.jpg" width="300" loading="lazy">⌠Not Specifying Dimensions
<img src="photo.jpg" alt="Photo"> <!-- Causes layout shift --><img src="photo.jpg" alt="Photo" width="800" height="600"> <!-- Better -->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