HTML Image Width and Height
You start reading an article on your phone. A paragraph catches your eye, and you move your thumb to scroll. Then, with no warning, the text jumps down the screen. A picture above it has just finished loading and pushed everything aside. You lose your place. Worse, you tap a button just as it moves, and you tap the wrong thing.
Almost everyone has felt this, and it is annoying enough that search engines measure it. The cure is two small attributes you may already have noticed: width and height. In this lesson, you will learn why they work, how to set them correctly, and how to combine them with CSS so your images stay steady and flexible.
What You Will Learnβ
- What causes the "jumping page," and what it is called
- How
widthandheightlet the browser reserve space - How to find and write the right values
- How to make images responsive while keeping the benefit
- How to use the CSS
aspect-ratioproperty for boxes and placeholders - How high-density screens fit in
- How to measure the problem and confirm the fix
- Common mistakes, and how to avoid them
The Problem: Layout Shiftβ
When a browser reads your HTML, it often finds an image before it has downloaded the file. It does not know how big the picture is yet, so it gives the image no space. The text after it sits right up against the previous content. Then the file arrives, and the browser makes room by pushing everything down.
That sudden movement is called a layout shift. Search engines add up all the shifts on a page into a score called Cumulative Layout Shift (CLS). A lower score means a steadier page.
| CLS score | What it means |
|---|---|
| 0.1 or less | Good. The page is stable |
| 0.1 to 0.25 | Needs improvement |
| More than 0.25 | Poor. Visitors will notice jumps |
Images without dimensions are one of the most common causes, and one of the easiest to fix.
The Fix: width and heightβ
Tell the browser the image's size in the HTML, so it can save the right amount of space before the file arrives.
- HTML Code
- Browser Output
<img
src="images/harbor.jpg"
alt="A small sailboat on blue waves under a bright sun"
width="240"
height="160"
/>
<p>This paragraph stays put, because the space above it is already reserved.</p>
This paragraph stays put, because the space above it is already reserved.
The demo uses a small drawing built into the page. In your project, src points to a real file.
The Rulesβ
- Write the values as plain numbers. They mean pixels, but you do not write
px. width="240"is correct.width="240px"andwidth="50%"are not valid in HTML. For percentages, use CSS.- Use the image's real dimensions (or the same proportions), not made-up numbers.
<!-- Correct -->
<img src="photo.jpg" alt="..." width="600" height="400" />
<!-- Not valid in HTML -->
<img src="photo.jpg" alt="..." width="600px" height="400px" />
<img src="photo.jpg" alt="..." width="100%" height="auto" />
How It Works Todayβ
Modern browsers do something clever with these two numbers. They calculate the aspect ratio (the proportion of width to height) and reserve space with exactly that shape, even when CSS later changes the displayed size.
For example, width="600" height="400" is a ratio of 3 to 2. If CSS makes the image 300 pixels wide on a phone, the browser still knows the height should be 200, and it reserves that space before the image loads.
That is why the best practice is:
- Put the image's real pixel width and height in the HTML.
- Use CSS to control the displayed size.
Combining With CSS: Steady and Flexibleβ
The next rule gives you images that never overflow, never stretch, and never cause a jump.
img {
max-width: 100%;
height: auto;
}
Here is what each part does.
| Part | What it does |
|---|---|
width="600" and height="400" in HTML | Tell the browser the proportions so it can reserve space |
max-width: 100% in CSS | Prevents the image from being wider than its container |
height: auto in CSS | Keeps the proportions when the width changes |
- Distorted
- Correct
/* The HTML says height="400", and CSS keeps it fixed.
When the width shrinks, the image is stretched tall. */
img {
max-width: 100%;
}
img {
max-width: 100%;
height: auto; /* height follows the width and the ratio */
}
The picture shrinks to fit its 180-pixel box and keeps its proportions.
height: autoIf you set a CSS width on an image but leave out height: auto, the HTML height attribute still applies. The picture can come out stretched or squashed.
How to Find the Right Numbersβ
You need the image's natural size in pixels.
| Where | How |
|---|---|
| Your computer | Right-click the file and open its properties or info |
| An image editor | Check the image size or canvas size |
| Command line | Use a tool such as file photo.jpg on many systems |
| Browser | Open the image in its own tab. Developer tools show its natural size |
| Your build tool or CMS | Many generate the dimensions automatically |
If you resize a photo before publishing, as you should, use the resized dimensions in your HTML.
Calculating a Missing Valueβ
If you know the ratio and one number, you can find the other.
height = width Γ (original height Γ· original width)
Original: 1200 Γ 800 (ratio 3:2)
You want a width of 600 β height = 600 Γ (800 Γ· 1200) = 400
Common Aspect Ratiosβ
| Ratio | Looks like | Common uses |
|---|---|---|
| 1 : 1 | Square | Avatars, product tiles |
| 4 : 3 | Slightly wide | Older photos, presentations |
| 3 : 2 | Wide | Camera photos |
| 16 : 9 | Widescreen | Video, banners |
| 9 : 16 | Tall | Phone stories |
The CSS aspect-ratio Propertyβ
Sometimes you need to reserve space for something that is not an <img>, such as a video box, a map, or a card whose image has not loaded yet. For those, CSS has the aspect-ratio property.
.video-box {
width: 100%;
aspect-ratio: 16 / 9;
background: #e2e8f0; /* a calm placeholder color */
}
.avatar {
width: 64px;
aspect-ratio: 1; /* same as 1 / 1: a square */
border-radius: 50%;
object-fit: cover;
}
Reserved 16:9 space
The box holds its 16 to 9 shape even when it is empty, so nothing jumps when the content arrives. A soft background color also gives visitors something calm to look at instead of a blank hole.
Images That Fill a Boxβ
When a design needs an image to fill a fixed shape, combine the box's ratio with object-fit, as you learned in The img Element.
.card-image {
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover;
}
Every card then has the same shape, whatever the original photos look like.
Dimensions and Sharpnessβ
The width and height in your HTML describe the image's real pixel size. They do not make the picture sharper or blurrier by themselves. But the relationship between the file size in pixels and the size on screen matters.
| Situation | Result |
|---|---|
| File is smaller than the display size | The browser stretches it, and it looks blurry |
| File is the same as the display size | Sharp on normal screens |
| File is twice the display size | Sharp on high-density ("retina") screens, but costs more data |
| File is much larger than needed | Sharp, but slow and wasteful |
High-density screens pack two or three device pixels into each CSS pixel. To look crisp on them, an image shown at 300 CSS pixels wide needs a file about 600 pixels wide. You do not want to send that big file to everyone, which is why you will learn srcset in Srcset and Sizes. It lets each device download the size it needs.
For a single image file, make it about twice the largest size it will be shown at, then compress it well. When you learn srcset, you can offer several sizes instead.
Special Casesβ
SVG Imagesβ
SVG graphics scale without losing quality, so they have no "natural" pixel size. Still, set width and height to reserve space and avoid shifts.
<img src="images/logo.svg" alt="CodeHarborHub home" width="140" height="40" />
Images That Change Shapeβ
If you show different crops on different screens with <picture>, set width and height on the <img> and, where the shapes differ, on each <source> too. You will see this in Picture Element.
Images Loaded Laterβ
For lazy-loaded images, width and height are even more important. The image arrives long after the page is built, and without reserved space, the jump is certain. Read more in Lazy Loading.
Checking the Resultβ
You can measure whether your fix worked.
- Open your browser's developer tools. Many have a Performance panel that highlights layout shifts.
- Run Lighthouse (built into Chrome-based browsers) or the free PageSpeed Insights service. Look at the CLS score and the list of "images without explicit dimensions."
- Throttle the network. Set the connection to "Slow 3G" and reload. Watch whether the content moves as images appear.
- Test on a real phone. Scroll while the page is still loading.
Common Mistakesβ
Mistake 1: Leaving out width and heightβ
The most common cause of jumping images. Add both to every <img>.
Mistake 2: Writing units or percentagesβ
width="300px" and width="50%" are invalid. Write width="300", and use CSS for percentages.
Mistake 3: Using made-up proportionsβ
Numbers that do not match the real image shape reserve the wrong amount of space, so the page still jumps a little, and your picture may look squashed.
Mistake 4: Forgetting height: autoβ
With a CSS width or max-width and no height: auto, the image is distorted.
Mistake 5: Stretching a small image to look bigβ
Enlarging a small file makes it blurry. Start with a file large enough.
Mistake 6: Sending enormous files and shrinking them with HTMLβ
width="300" on a 5000-pixel photo downloads all 5000 pixels. Resize the file itself.
Mistake 7: Forgetting space for non-image contentβ
Ads, videos, and embeds need reserved space too. Use aspect-ratio or fixed-size boxes.
Mistake 8: Squashing a logo with width and height that do not matchβ
Keep a logo's proportions, or it will look wrong.
Try It Yourselfβ
Here is a short project.
- Create
steady.htmlwith three pictures of different shapes: square, wide, and tall. - Find the real width and height of each one and write them in the HTML.
- Add
img { max-width: 100%; height: auto; }and resize your browser window. Do the images keep their shapes? - Remove
height: autoand test again. What changes? - In developer tools, set the network to "Slow 3G" and reload. Remove the
widthandheightfrom one image and compare how the page moves. - Create a
.video-boxwithaspect-ratio: 16 / 9and a soft background color. - Make a row of four cards with
aspect-ratio: 4 / 3andobject-fit: cover. - Run Lighthouse and note your CLS score.
Quick Recapβ
Click a question to check your answer.
1. What does Cumulative Layout Shift measure?
How much page content moves around unexpectedly while the page loads. Lower scores mean a steadier page.
2. How do width and height in HTML prevent layout jumps?
They let the browser work out the image's aspect ratio, so it can reserve the right amount of space before the file arrives.
3. Should you write width="300px"?
No. The attributes take plain numbers that mean pixels. Use CSS for units and percentages.
4. What two CSS lines make images responsive without distortion?
max-width: 100%; and height: auto;.
5. When would you use the CSS aspect-ratio property?
To reserve a box of a certain shape for content that is not an <img>, such as a video, a map, or an image placeholder.
Key Takeawaysβ
- Missing image sizes cause layout shift, which annoys visitors and lowers your page-quality scores.
- Write
widthandheightin HTML as plain numbers, using the image's real proportions. - Add
max-width: 100%andheight: autoin CSS so images are flexible without distortion. - Use
aspect-ratioto reserve space for boxes, videos, and placeholders. - Resize files to the right size, and measure your result with developer tools or Lighthouse.
Your images now hold their place. Next, learn which file types to choose in Image Formats.