Working with Images in HTML
1. The <img> Tag
Images are displayed in HTML using the <img> element.
The most important attribute is src, which defines the image source:
Code Block Loading...
Supported Formats
Common image formats include PNG, JPEG, GIF, SVG, and the more modern WebP.
Accessibility with alt
The HTML standard requires an alt attribute to describe the image. This helps screen readers and search engines understand the content:
Code Block Loading...
Dimensions
You can set width and height (in pixels) to reserve space before the image loads, preventing layout shifts:
Code Block Loading...
2. The <figure> Tag
The <figure> element is a semantic wrapper often used with images, especially when paired with a caption.
Code Block Loading...
<figcaption>provides descriptive text for the image.- This improves accessibility and semantic meaning.
3. Responsive Images with srcset
The srcset attribute lets browsers choose the most appropriate image based on screen size or pixel density. This ensures efficient loading—mobile devices won’t download unnecessarily large files.
Example:
Code Block Loading...
Here, w specifies the image’s width in pixels.
To make this work properly, you also need the sizes attribute:
Code Block Loading...
How sizes Works
(max-width: 500px) 100vw→ if viewport < 500px, image fills 100% of width.(max-width: 900px) 50vw→ if viewport < 900px, image fills 50% of width.800px→ otherwise, image is fixed at 800px wide.
Tip: vw = 1% of viewport width. So 100vw = full width of the window.
A handy tool for generating responsive images: responsivebreakpoints.com.
4. The <picture> Tag
The <picture> element provides more flexibility than srcset. Instead of just resizing, it allows you to serve different formats or entirely different images depending on browser support or media queries.
Format Fallback Example
Code Block Loading...
- Browsers that support WebP will load
image.webp. - Others will fall back to
image.png.
Media Query Example
Code Block Loading...
While possible, this approach is verbose. The <picture> tag is best used when switching formats (e.g., WebP vs JPEG), not just resizing.
Browser Support
- Supported by all major browsers.
- Not supported in Opera Mini and Internet Explorer.
With <img>, <figure>, srcset, and <picture>, you can create accessible, responsive, and optimized images for modern web design.