HTML & CSSEasy
What is the <img> tag?
<img> embeds an image. It is a void element that needs src (the image URL) and alt (a text alternative), and should have width and height so the browser reserves space and avoids layout shift. Modern attributes like srcset, sizes, loading="lazy", decoding and fetchpriority make images responsive and fast.
Essential attributes
src: the image file.alt: describes the image for screen readers and when it fails to load;alt=""for decorative images.widthandheight: intrinsic size in pixels; the browser uses the ratio to reserve space before loading (prevents Cumulative Layout Shift). CSS can still resize it (max-width: 100%; height: auto).
Performance attributes
srcset+sizes: let the browser choose the best file for the screen size and pixel density.loading="lazy": defer offscreen images. Do not lazy-load the main above-the-fold image.fetchpriority="high": prioritize the Largest Contentful Paint image.decoding="async": decode off the main thread.
Formats
- AVIF and WebP for photos (much smaller than JPEG), JPEG as fallback.
- SVG for icons and logos.
- PNG when you need lossless images with transparency.
- Use
<picture>to offer multiple formats with fallbacks.
Accessibility
Write alt text that conveys purpose: for a linked logo, use the destination ("DevQnA home"); for informative charts, summarize the data.
Common mistakes
Missing alt, missing dimensions, huge images scaled down with CSS, and lazy-loading the hero image.
Code example
html
1<style>2 body { font-family: system-ui; }3 img { max-width: 100%; height: auto; border-radius: 8px; } /* responsive while keeping aspect ratio */4</style>56<!-- Hero image: high priority, not lazy, responsive sizes -->7<img8 src="https://picsum.photos/id/1015/800/400"9 srcset="https://picsum.photos/id/1015/400/200 400w, https://picsum.photos/id/1015/800/400 800w, https://picsum.photos/id/1015/1600/800 1600w"10 sizes="(max-width: 600px) 100vw, 800px"11 width="800" height="400"12 alt="River winding through a mountain valley"13 fetchpriority="high">1415<!-- Offscreen image: lazy loaded -->16<img src="https://picsum.photos/id/1025/400/300" width="400" height="300" loading="lazy" decoding="async"17 alt="Pug wrapped in a blanket">1819<!-- Decorative image: empty alt so screen readers skip it -->20<img src="https://picsum.photos/id/1040/400/40" width="400" height="40" alt="">
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.