Image Sizing & Aspect Ratios
Overview
When a browser loads a web page, it reads the HTML instantly, but it takes time to download the images. If the browser doesn't know how big the image is going to be, it will draw the page, and then when the image finally loads, the layout will violently jump down to make room for the picture.
This is called 'Cumulative Layout Shift' (CLS), and it is incredibly frustrating for users (imagine trying to click a button, but an image loads and pushes the button down, making you click the wrong thing!).
Syntax
You should ALWAYS provide the `width` and `height` attributes (in raw numbers, representing pixels) on your `<img>` tags. This reserves a blank box of the exact correct size while the image downloads.
<!-- The browser instantly reserves a 600x400 box on the screen -->
<img
src="heavy-hero-image.jpg"
alt="Beautiful landscape"
width="600"
height="400"
/>Even if you set `width="600"` in HTML, you can still use CSS to make the image responsive (e.g., `width: 100%`). The HTML width/height attributes just tell the browser the *Aspect Ratio* (the proportion of width to height) so it calculates the spacing correctly.
<!-- HTML -->
<img class="responsive-img" src="photo.jpg" width="800" height="800" />
<!-- CSS -->
<style>
.responsive-img {
width: 100%; /* Scales to fit the phone screen */
height: auto; /* Maintains the 800:800 (1:1) square aspect ratio */
}
</style>Common Pitfalls
- Do NOT use 'px' or '%' in the HTML width/height attributes. Just write the raw numbers. (e.g., width='500' ✅, width='500px' ❌).
- Interview tip: Core Web Vitals (Google's ranking metric) heavily penalizes websites with Layout Shifts. Adding width and height to your images is the #1 way to fix CLS scores.
Real-World Example
A modern, performant image tag solving Layout Shift:
<article>
<h2>My Vacation</h2>
<!-- Reserves space, loads lazily, and prevents layout shifts! -->
<img
src="/images/beach.webp"
alt="Sandy beach in Goa"
width="1920"
height="1080"
loading="lazy"
decoding="async"
style="width: 100%; height: auto;"
/>
<p>The beach was amazing...</p>
</article>