How to Set Image Height and Width in HTML
Set intrinsic image dimensions correctly, keep layouts stable, make images responsive, and avoid distortion with practical HTML and CSS examples.
Use unitless pixel values in the HTML width and height attributes, then use CSS to control the rendered size.
<img
src="photo.jpg"
alt="A mountain at sunrise"
width="1200"
height="800">
The attributes describe the image’s intrinsic dimensions. They let the browser calculate the aspect ratio and reserve the correct space before the file finishes downloading, which helps prevent layout shifts. In HTML, values are integer pixels without units such as px.
Correct image width and height syntax
Put width and height directly on the img element. Use the source file’s actual dimensions, or dimensions with the same ratio as the source.
<img src="hero-1600.jpg"
alt="A mountain at sunrise"
width="1600"
height="1067">
| Part | What it does | Example |
|---|---|---|
src |
Image URL or path | photo.jpg |
alt |
Text alternative for accessibility and failed loads | A mountain at sunrise |
width |
Intrinsic width in pixels; unitless in HTML | 1200 |
height |
Intrinsic height in pixels; unitless in HTML | 800 |
Do not write width="1200px" or height="800px". CSS accepts units; these HTML attributes do not.
Make images responsive without stretching
Keep the intrinsic attributes and add proportional CSS:
img {
max-width: 100%;
height: auto;
}
max-width: 100% allows an image to shrink to its containing block. height: auto keeps the natural aspect ratio. The image can display smaller than its intrinsic size, but it will not be stretched to an unrelated height.
<figure class="article-media">
<img
src="photo-1200.jpg"
alt="A mountain at sunrise"
width="1200"
height="800">
<figcaption>Sunrise over the ridge.</figcaption>
</figure>
.article-media {
margin: 0;
}
.article-media img {
display: block;
max-width: 100%;
height: auto;
}
When to use a deliberate ratio
Cards, galleries and video-like thumbnails often need a fixed visual ratio even when source images differ. Use aspect-ratio and choose the crop behavior with object-fit:
.card-media {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
display: block;
}
.contained-media {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: contain;
display: block;
background: #eee;
}
cover fills the box and may crop the edges. contain shows the complete image and may leave empty space. On a replaced element such as img, the natural ratio can be used after the content loads; declaring aspect-ratio gives the component a predictable box earlier.
Choose efficient sources with srcset and sizes
If you have several files, srcset and sizes let the browser select an appropriate candidate for the viewport and display width.
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w,
photo-800.jpg 800w,
photo-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 800px"
width="1600"
height="1067"
alt="A mountain at sunrise">
The width and height attributes still matter. Keep their ratio consistent with the intrinsic dimensions represented by the image set so the browser reserves accurate space before choosing and decoding a candidate.
Pixel-density candidates
For a component with a known CSS width, density descriptors are another option:
<img
src="avatar-200.jpg"
srcset="avatar-200.jpg 1x, avatar-400.jpg 2x"
width="200"
height="200"
alt="Profile photo of Sam"></img>
Use either a consistent w-descriptor set with sizes, or a density set such as 1x and 2x. Do not mix descriptor types in one srcset.
Accessibility requirements
Give informative images meaningful alternative text:
<img src="chart.png" width="900" height="500"
alt="Quarterly revenue increased from Q1 to Q4">
For decorative images, use an empty attribute so assistive technology skips them:
<img src="divider.svg" width="1200" height="24" alt="">
Do not omit alt. The alternative is read by screen readers and can be shown when the image cannot load.
Prevent layout shifts on lazy-loaded images
Below-the-fold images should retain intrinsic dimensions even when loading is deferred:
<img
src="gallery-800.jpg"
width="800"
height="533"
loading="lazy"
decoding="async"
alt="Coastal path at dusk">
The dimensions reserve the expected box while the file is fetched. Lazy loading is useful for content below the initial viewport; avoid applying it indiscriminately to the main above-the-fold image.
Common mistakes and fixes
| Problem | Cause | Fix |
|---|---|---|
| Image is stretched | A fluid width is paired with an unrelated fixed CSS height. | Use height: auto, or use a deliberate aspect-ratio with object-fit. |
| HTML validation or ignored dimensions | px was placed in the HTML attribute. |
Use integers such as width="1200"; put units in CSS. |
| Page jumps when the image appears | Intrinsic dimensions were omitted, especially on lazy-loaded content. | Add matching width and height attributes. |
| Unexpected crop | object-fit: cover fills a box with a different ratio. |
Use contain for the full image, or choose a suitable crop position with object-position. |
| Blurry image | The selected source is too small for the rendered size or display density. | Provide larger candidates in srcset and accurate sizes. |
| Wrong space reserved | The attributes do not match the source ratio. | Use the source’s intrinsic dimensions or preserve the same ratio. |
| Image is missing | The URL is incorrect, the server returns an error, or the resource is blocked. | Open the URL directly, inspect the network response, and check server permissions and MIME type. |
Debugging checklist
- Inspect the rendered element and confirm that
widthandheightare numeric HTML attributes. - Check the computed CSS for a conflicting fixed height or width.
- Compare the attribute ratio with the image file’s intrinsic ratio.
- In browser developer tools, inspect the network request, status code, response headers and selected
srcsetcandidate. - Test narrow and wide viewports to verify the
sizesexpression. - Confirm that meaningful images have useful
alttext and decorative images usealt="".
Performance and reliability considerations
- Intrinsic dimensions reduce reflow because the browser can allocate the image box before decoding completes.
- Responsive candidates can reduce transfer size on small screens, while an accurate
sizesvalue prevents selecting an unnecessarily large file. - Keep the source ratio and attributes aligned; a wrong ratio can reserve the wrong space even when the final image looks correct.
- Use
loading="lazy"for off-screen images when appropriate, and keep critical hero imagery available for the initial render. - Use
object-fitonly when the component design accepts cropping or empty letterbox space. - Serve stable image URLs and configure your image host to return the correct content type and cache behavior.
Capture an example page for visual checks
When you need to verify that image dimensions, responsive rules and reserved space look right at a real viewport, capture the page after it renders. ScreenshotNeo provides a website screenshot API and MCP server for developers. Its clean capture flow accepts consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets before the shot; each step can be turned off.
Or skip the browser setup
Use one request to capture a page while you review the rendered result. See the ScreenshotNeo documentation for options such as viewport and device presets, full-page capture, waiting for a selector or network idle, custom CSS and JavaScript, and image formats.
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://example.com/image-test \
-o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://example.com/image-test"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://example.com/image-test'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const bytes = await res.arrayBuffer();
await Bun.write('shot.webp', bytes);
Bot checks and CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing; the response identifies the result with X-Page-Verdict and X-Billed headers. An MCP server lets Claude, Cursor and other MCP clients call take_screenshot, get_page_info and capture_pdf. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
FAQ
Are HTML width and height measured in pixels?
Yes. They are unitless integer pixel dimensions that describe the intrinsic image size.
Can CSS override the HTML attributes?
Yes. CSS controls the rendered size. Keep the attributes for the intrinsic ratio and early space reservation.
Should width and height always match the file exactly?
They should match the file’s dimensions or preserve its exact aspect ratio. A matching ratio is what prevents incorrect reserved space.
How do I make every thumbnail the same shape?
Set the component’s aspect-ratio, then choose object-fit: cover for a filled crop or contain to show the complete image.
What is the difference between srcset and CSS resizing?
CSS changes display size after a resource is selected. srcset and sizes help the browser select a resource suited to the display width and resolution before downloading.
Reference
See MDN’s img element reference and Images in HTML guide for the platform behavior behind intrinsic dimensions, alternative text and responsive image selection.


