Preventing Layout Shift with width and height Attributes
You'll learn how setting explicit width and height attributes on images helps browsers reserve the correct space before the image loads, eliminating jarring layout shifts.
The Problem: Layout Jumping
When a browser encounters an <img> tag without size information, it initially renders a zero-height placeholder. Once the image file downloads and the browser discovers its dimensions, the page suddenly reflows to make room—pushing content down and creating a frustrating "jump" (called Cumulative Layout Shift or CLS). This disrupts reading and can cause users to accidentally click the wrong thing.
The Solution: Width and Height Attributes
By adding width and height attributes directly to your <img> tags, you give the browser crucial information before the image loads:
<img
src="photo.jpg"
alt="A mountain landscape"
width="800"
height="600"
>
Modern browsers use these values to calculate the aspect ratio (800÷600 = 1.33:1). Even if CSS makes the image responsive (max-width: 100%), the browser reserves space with the correct proportions immediately during page parsing.
How It Works with Responsive CSS
You don't need to worry about the image being locked at 800×600 pixels. When you combine the attributes with responsive CSS:
img {
max-width: 100%;
height: auto;
}
The browser uses the width and height attributes to maintain aspect ratio while the CSS makes it fluid. The space is reserved correctly at any viewport size.
Think of It Like This
Setting width and height is like telling a parking valet the size of your car before you arrive—they can mark off the right amount of space in advance, preventing other cars from being repositioned when you show up.
Key Takeaway: Always include width and height attributes on <img> tags to let browsers calculate aspect ratios early and prevent content from jumping around as images load.