Image Size and Alt Text

Control image dimensions and provide good alternative text.

Syntax<img src="pic.jpg" alt="A cat" width="200" height="150">

You can set the display size of an image with the width and height attributes, measured in pixels.

Setting the size helps the browser reserve space so the page does not jump while the image loads.

Writing good alt text

  • Describe what the image shows.
  • Keep it short and meaningful.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A developer sets explicit width and height on all <img> tags to prevent cumulative layout shift (CLS) while images load.
  • A responsive layout uses CSS max-width: 100% to ensure images scale down on mobile without setting fixed pixel sizes in HTML.
  • A performance engineer uses srcset to serve a 400px image on mobile and an 1200px image on desktop, reducing data use.

More examples

Fixed width and height attributes

Setting width and height reserves the exact space in the layout before the image loads, preventing reflow.

Example · html
<img src="card-thumb.jpg"
     alt="Course thumbnail"
     width="320"
     height="200"
>

Responsive image with CSS

HTML attributes provide the natural ratio; CSS max-width and auto height make it scale responsively.

Example · html
<img src="banner.jpg"
     alt="Summer sale banner"
     width="1200"
     height="400"
     style="max-width: 100%; height: auto;"
>

srcset for resolution-based sizing

srcset with sizes lets the browser download only the image resolution appropriate for the current screen.

Example · html
<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: 1024px) 800px, 1200px"
  alt="Mountain landscape"
>

Discussion

  • Be the first to comment on this lesson.
Image Size and Alt Text — HTML | SoundsCode