Image Display
HTML Tutorial
Web Development
Coding Guide
Beginners Guide

How to display an image

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Displaying images on a web page is one of the first things you learn in web development, yet there is surprising depth to doing it well. A properly implemented image is fast to load, accessible to all users, and adapts to different screen sizes. This article covers the fundamental HTML img tag, responsive image techniques, CSS background images, lazy loading, accessibility best practices, and modern image formats so you can handle images confidently in any project.

The HTML img Tag

The img element is the standard way to embed an image in an HTML document. It is a self-closing tag that requires at minimum a src attribute pointing to the image file and an alt attribute describing the image:

html
1<img
2  src="photo.jpg"
3  alt="A golden retriever playing fetch in a park"
4  width="800"
5  height="600"
6/>

The src attribute accepts a relative path, an absolute path, or a full URL. The width and height attributes tell the browser the image dimensions before it loads, which prevents layout shift (the page content jumping around as images load). Always include these attributes even if you plan to resize the image with CSS, because they establish the aspect ratio for the browser's layout engine.

html
1<!-- Relative path -->
2<img src="images/logo.png" alt="Company logo" width="200" height="50" />
3
4<!-- Absolute URL -->
5<img
6  src="https://example.com/banner.jpg"
7  alt="Summer sale banner"
8  width="1200"
9  height="400"
10/>

Responsive Images with srcset and sizes

On the modern web, visitors use devices ranging from small phones to large desktop monitors. Serving the same large image to every device wastes bandwidth on mobile and can look blurry on high-density screens. The srcset and sizes attributes solve this:

html
1<img
2  src="photo-800.jpg"
3  srcset="
4    photo-400.jpg   400w,
5    photo-800.jpg   800w,
6    photo-1200.jpg 1200w,
7    photo-1600.jpg 1600w
8  "
9  sizes="(max-width: 600px) 100vw,
10         (max-width: 1200px) 50vw,
11         800px"
12  alt="Mountain landscape at sunset"
13  width="1600"
14  height="900"
15/>

The srcset attribute lists available image files with their intrinsic widths (using the w descriptor). The sizes attribute tells the browser how wide the image will be displayed at various viewport sizes. The browser then picks the best file to download. This is purely a performance optimization and the browser has the final say in which image it selects.

For art direction (showing entirely different crops on different screens), use the picture element:

html
1<picture>
2  <source media="(max-width: 600px)" srcset="hero-mobile.jpg" />
3  <source media="(max-width: 1200px)" srcset="hero-tablet.jpg" />
4  <img src="hero-desktop.jpg" alt="Product showcase" width="1600" height="800" />
5</picture>

The browser uses the first source whose media query matches, falling back to the img tag if none match.

CSS Background Images

When an image is decorative (not content), CSS background images are appropriate. They do not appear in the document flow and are ignored by screen readers:

css
1.hero-section {
2  background-image: url('hero-bg.jpg');
3  background-size: cover;
4  background-position: center;
5  background-repeat: no-repeat;
6  min-height: 500px;
7}
html
<section class="hero-section">
  <h1>Welcome to Our Site</h1>
</section>

Use background-size: cover to ensure the image fills its container regardless of aspect ratio. Use background-size: contain if the entire image must be visible. Background images cannot have alt text, so they should never be used for images that convey meaning to the user.

Lazy Loading

Images below the fold (outside the initial viewport) do not need to load immediately. The loading="lazy" attribute defers loading until the user scrolls near the image:

html
1<!-- Loads immediately (above the fold) -->
2<img
3  src="hero.jpg"
4  alt="Hero banner"
5  width="1200"
6  height="600"
7  loading="eager"
8/>
9
10<!-- Loads when user scrolls near it -->
11<img
12  src="gallery-photo-5.jpg"
13  alt="Beach at sunset"
14  width="800"
15  height="600"
16  loading="lazy"
17/>

This is a native browser feature that requires no JavaScript. Do not apply loading="lazy" to images that are visible on initial page load (like the hero image), because it can delay their appearance and hurt perceived performance. Apply it to images further down the page, in galleries, or in content that users may not scroll to.

Accessibility: Alt Text Best Practices

The alt attribute is essential for accessibility. Screen readers read it aloud to visually impaired users, and it displays when an image fails to load. Writing good alt text is a skill:

html
1<!-- Good: describes what the image shows -->
2<img src="chart.png" alt="Bar chart showing revenue growth from 2M in 2020 to 8M in 2024" />
3
4<!-- Good: empty alt for decorative images -->
5<img src="decorative-border.png" alt="" />
6
7<!-- Bad: uninformative -->
8<img src="chart.png" alt="image" />
9<img src="chart.png" alt="chart.png" />

Guidelines for effective alt text include describing the content and function of the image (not just its appearance), keeping it concise (under 125 characters when possible), and never starting with "image of" or "picture of" since screen readers already announce it as an image. For purely decorative images, set alt="" so screen readers skip them entirely.

The figure and figcaption Elements

When an image is a self-contained piece of content that benefits from a caption (like a photo in an article or a diagram), wrap it in figure and add a figcaption:

html
1<figure>
2  <img
3    src="architecture-diagram.png"
4    alt="System architecture showing three microservices connected through a message queue"
5    width="900"
6    height="500"
7  />
8  <figcaption>
9    Figure 1: The system architecture uses a message queue to decouple
10    the order, payment, and notification services.
11  </figcaption>
12</figure>

The figcaption provides a visible caption that all users can see, while the alt attribute serves as a text alternative for assistive technology. They serve different purposes and both should be present.

Common Image Formats

Choosing the right format affects both quality and file size. JPEG is the standard for photographs because it handles millions of colors efficiently with lossy compression. PNG supports transparency and is ideal for logos, icons, and graphics with sharp edges. WebP offers 25-35% better compression than JPEG for equivalent quality and supports transparency. AVIF is the newest format with even better compression than WebP but has less browser support.

html
1<!-- JPEG: best for photographs, no transparency -->
2<img src="photo.jpg" alt="Portrait photo" width="800" height="600" />
3
4<!-- PNG: best for graphics with transparency or sharp edges -->
5<img src="logo.png" alt="Company logo with transparent background" width="200" height="80" />
6
7<!-- WebP: modern format with better compression -->
8<img src="photo.webp" alt="Compressed landscape photo" width="800" height="600" />
9
10<!-- Use picture element for format fallback -->
11<picture>
12  <source srcset="photo.avif" type="image/avif" />
13  <source srcset="photo.webp" type="image/webp" />
14  <img src="photo.jpg" alt="Landscape photo" width="800" height="600" />
15</picture>

The picture element lets you serve modern formats to browsers that support them while falling back to JPEG for older browsers.

Common Pitfalls

  • Missing width and height attributes means the browser cannot reserve space for the image, causing layout shift as images load and hurting Core Web Vitals scores.
  • Omitting the alt attribute entirely (not the same as alt="") makes the image inaccessible and may cause screen readers to announce the raw file name.
  • Applying loading="lazy" to above-the-fold images like the hero banner delays their appearance and worsens the Largest Contentful Paint metric.
  • Serving unoptimized images straight from a camera without resizing or compressing leads to multi-megabyte downloads and slow page loads.
  • Using CSS background images for meaningful content removes the image from the accessibility tree, making it invisible to screen readers.

Summary

  • The img tag with src, alt, width, and height is the foundation for displaying images in HTML.
  • Use srcset and sizes for responsive images that serve the right file size to each device, and picture for art direction across breakpoints.
  • CSS background images are appropriate for decorative visuals that do not convey content meaning.
  • Native lazy loading with loading="lazy" defers off-screen images to improve initial page load performance.
  • Write descriptive alt text for content images and use alt="" for decorative ones. Wrap captioned images in figure with figcaption.
  • Prefer modern formats like WebP and AVIF with JPEG fallbacks using the picture element for the best balance of quality and file size.

Course illustration
Course illustration

All Rights Reserved.