img Element
The \<img\> element embeds images into HTML documents.
Basic Usage
<!-- Simple image -->
<img src="photo.jpg" alt="A beautiful sunset">
<!-- With dimensions -->
<img src="logo.png" alt="Company Logo" width="200" height="100">
<!-- Lazy loading -->
<img src="image.jpg" alt="Description" loading="lazy">
<!-- Image with figure caption -->
<figure>
<img src="chart.png" alt="Sales chart showing growth">
<figcaption>Figure 1: Quarterly sales growth</figcaption>
</figure>
Required Attributes
| Attribute | Purpose | Required? |
|---|---|---|
src |
Image URL/path | Yes |
alt |
Alternative text | Yes (accessibility) |
Common Attributes
| Attribute | Purpose | Example |
|---|---|---|
width |
Display width (px) | width="300" |
height |
Display height (px) | height="200" |
loading |
Lazy loading | loading="lazy" |
decoding |
Decode asynchronously | decoding="async" |
srcset |
Multiple image sources | See responsive images |
sizes |
Screen size hints | See responsive images |
Alt Text Best Practices
<!-- ❌ Bad alt text -->
<img src="photo.jpg" alt="">
<img src="photo.jpg" alt="image">
<img src="photo.jpg" alt="photo.jpg">
<img src="photo.jpg" alt="photo of a dog sitting on a chair in a park on a sunny day with trees in the background">
<!-- ✅ Good alt text -->
<img src="dog.jpg" alt="Golden retriever sitting in park">
<img src="chart.png" alt="Sales increased 25% in Q4">
<img src="logo.png" alt="">
<!-- Empty alt for decorative images -->
When to Use Empty Alt
<!-- Decorative images: empty alt -->
<img src="decoration.png" alt="">
<!-- Functional images (icons): descriptive alt -->
<img src="search-icon.png" alt="Search">
<!-- Informative images: describe content -->
<img src="infographic.png" alt="Infographic showing 5 steps to clean code">
<!-- Images with text: include all text -->
<img src="banner.png" alt="Sale! 50% off all items">
Responsive Images
Responsive images adapt to different screen sizes and device capabilities.
srcset for Resolution Switching
<!-- Serve different images based on pixel density -->
<img src="photo-1x.jpg"
srcset="photo-1x.jpg 1x, photo-2x.jpg 2x, photo-3x.jpg 3x"
alt="Responsive image">
<!-- Serve different images based on viewport width -->
<img src="photo-800.jpg"
srcset="photo-400.jpg 400w,
photo-800.jpg 800w,
photo-1200.jpg 1200w"
sizes="(max-width: 600px) 100vw,
(max-width: 1200px) 50vw,
800px"
alt="Responsive image">
Picture Element for Art Direction
<!-- Show different crops for different screen sizes -->
<picture>
<source media="(min-width: 1200px)" srcset="landscape.jpg">
<source media="(min-width: 600px)" srcset="tablet.jpg">
<img src="mobile.jpg" alt="Product photo">
</picture>
<!-- Serve different formats -->
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Photo">
</picture>
art direction use case
<!-- Desktop: wide landscape -->
<!-- Tablet: cropped -->
<!-- Mobile: square crop -->
<picture>
<source media="(min-width: 1024px)"
srcset="hero-wide.jpg"
type="image/jpeg">
<source media="(min-width: 640px)"
srcset="hero-medium.jpg"
type="image/jpeg">
<img src="hero-square.jpg"
alt="Hero image"
loading="lazy">
</picture>
Lazy Loading
<!-- Native lazy loading -->
<img src="image.jpg" alt="Description" loading="lazy">
<!-- JavaScript lazy loading with Intersection Observer -->
<img data-src="image.jpg" alt="Description" class="lazy">
<script>
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
document.querySelectorAll('img.lazy').forEach(img => {
observer.observe(img);
});
</script>
Image Formats
Different image formats have different characteristics and use cases.
Format Comparison
| Format | Transparency | Animation | Best For | Size |
|---|---|---|---|---|
| JPEG | No | No | Photos | Small |
| PNG | Yes | No | Graphics, screenshots | Medium |
| GIF | Yes | Yes | Simple animations | Large |
| WebP | Yes | Yes | All types (modern) | Smallest |
| AVIF | Yes | Yes | All types (newer) | Smallest |
When to Use Each
<!-- Photos: JPEG or WebP -->
<img src="photo.jpg" alt="Photo">
<img src="photo.webp" alt="Photo (modern)">
<!-- Graphics/Logos: PNG or SVG -->
<img src="logo.png" alt="Logo">
<img src="icon.svg" alt="Icon">
<!-- Animations: GIF, WebP, or video -->
<img src="animation.gif" alt="Animated">
<img src="animation.webp" alt="Animated (modern)">
<!-- Transparent backgrounds: PNG, WebP, or AVIF -->
<img src="overlay.png" alt="Overlay">
<img src="overlay.webp" alt="Overlay (modern)">
Modern Format Support
<!-- Use picture to serve modern formats with fallback -->
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Photo">
</picture>
<!-- Check support in JavaScript -->
<script>
function supportsFormat(format) {
const canvas = document.createElement('canvas');
return canvas.toDataURL(`image/${format}`).indexOf(`data:image/${format}`) === 0;
}
if (supportsFormat('webp')) {
// Use WebP
} else {
// Use JPEG/PNG fallback
}
</script>
Image Optimization Tips
<!-- 1. Use appropriate dimensions -->
<img src="photo-800.jpg" alt="" width="800" height="600">
<!-- Don't load 4000px image for 800px display -->
<!-- 2. Use lazy loading for below-fold images -->
<img src="image.jpg" alt="" loading="lazy">
<!-- 3. Use modern formats -->
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="">
</picture>
<!-- 4. Set explicit dimensions (prevents layout shift) -->
<img src="image.jpg" alt="" width="300" height="200">
Practice Problems
Create a reusable React component implementing Images. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Images using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Images for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What is the purpose of the alt attribute?
2. When should you use an empty alt attribute?
3. What is the benefit of loading="lazy"?
4. Which format is best for photos?
Flashcards
Question
When should you use an empty alt attribute?
Click to reveal answer
Answer
For decorative images that don't convey meaning. Screen readers will skip them.
Question
What is the difference between srcset and picture?
Click to reveal answer
Answer
srcset provides multiple sources for resolution switching. picture provides art direction (different crops/sizes).
Question
What is lazy loading?
Click to reveal answer
Answer
Deferring image loading until the image is near the viewport. Improves initial page load performance.
Question
What is the best image format for modern web?
Click to reveal answer
Answer
WebP or AVIF for best compression. Use picture element with JPEG fallback for older browsers.
Question
What is Images?
Click to reveal answer
Answer
Images is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.Always provide meaningful alt text for accessibility
- 2.Use loading="lazy" for below-fold images
- 3.Use picture element for art direction
- 4.Modern formats (WebP, AVIF) provide better compression
- 5.Set explicit width/height to prevent layout shift
Interview Tips
- •Know when to use empty alt vs descriptive alt
- •Understand responsive image techniques
- •Be familiar with image format trade-offs
- •Know how lazy loading works
Cheat Sheet
Images Cheat Sheet
img Element:
Responsive Images:
- srcset: Resolution switching
- sizes: Viewport size hints
- picture: Art direction
Image Formats:
- JPEG: Photos (no transparency)
- PNG: Graphics (transparency)
- WebP: Modern, best compression
- AVIF: Newest, best quality
- SVG: Icons, illustrations
Best Practices:
- Always include alt text
- Use loading="lazy" for below-fold
- Set explicit width/height
- Use modern formats with fallbacks
- Optimize file sizes