CodeBlanks Logo Icon CodeBlanks

Image dimensions

HTML course · Beginner · Lesson 36/68

Learn the width and height attributes and their benefits.

The width and height attributes

The width and height attributes set the image size in pixels. The value is a plain number, no unit: width="640" height="360". The browser reserves that space on the page.

Stating the size prevents layout shift: as the image loads, the text below it is not suddenly pushed down, because the browser already reserved the box. The page feels smoother to the user.

Intrinsic size

The intrinsic size of an image is the pixel size stored in the file itself. Without width and height the browser shows the image at its intrinsic size, but it cannot know that size until the image has loaded.

Setting width and height as HTML attributes also preserves the aspect ratio. Even if you resize with CSS, the ratio is kept; the image is not squashed or stretched.

Exercise Add a sized image

Add an <img> element to body. Include src, alt, width and height. Set width 640 and height 360.

Show example solution
<body>
  <img src="https://example.com/city/square.jpg" alt="City square" width="640" height="360">
</body>

Test yourself

  1. What does setting width and height prevent?

    • Layout shift and sudden content jumps
    • The image loading slowly
    • The alternative text showing up
    • The page reloading
    Show answer

    Layout shift and sudden content jumps — Correct. With size known in advance the browser reserves the space and content does not jump.

  2. Complete the width value

    <img src="https://example.com/city/square.jpg" alt="City square" width="____" height="360">
    Show answer
    <img src="https://example.com/city/square.jpg" alt="City square" width="640" height="360">
  3. Match size concepts

    width
    Width (pixels)
    height
    Height (pixels)
    intrinsic size
    File's own size
    aspect ratio
    Width to height ratio

All lessons in Beginner