Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set an image’s intrinsic dimensions with unitless pixel values on the HTML <img> element, then use CSS for the size it should occupy on screen:

<img src="photo.jpg" alt="A mountain at sunrise" width="1200" height="800">

The width and height attributes tell the browser the source image’s dimensions and aspect ratio before the file finishes downloading. That lets it reserve the correct space and prevents surrounding content from jumping. Do not put px in these HTML attributes. For a fluid layout, keep the attributes and add max-width: 100%; height: auto in CSS.

HTML width and height syntax

Both attributes take positive, unitless integers. The numbers represent pixels in the image’s intrinsic coordinate system, not a CSS measurement with a unit.

<img
  src="photo.jpg"
  alt="A mountain at sunrise"
  width="1200"
  height="800">
  • src: the image URL or path.
  • alt: a text replacement for people using screen readers or when the image cannot load.
  • width and height: the source image’s intrinsic dimensions, expressed as integers without units.

Use the actual pixel dimensions, or the dimensions represented by the source set you serve. A 1200 × 800 image has a 3:2 ratio, so the browser can infer that ratio even before it receives the image bytes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

What not to write

<!-- Incorrect: CSS units do not belong in HTML attributes -->
<img src="photo.jpg" width="1200px" height="800px" alt="...">

CSS units are valid in a stylesheet or a style declaration, not in the HTML attribute values. Also avoid inventing dimensions that do not match the file; an incorrect ratio causes a visible correction when the image loads.

Why both attributes matter before the image loads

Images are replaced elements: the browser lays out a box for them while it fetches the resource. When both intrinsic dimensions are present, it can calculate the aspect ratio in advance and reserve the right amount of space. Without them, a below-the-fold or lazy-loaded image may initially have little or no height, pushing text and controls downward when the response arrives.

Keeping dimensions in the markup improves layout stability and makes loading behavior predictable. It does not force the image to render at that exact size; CSS can still make it smaller, larger, or fluid. The attributes provide the starting ratio and reservation, while CSS controls presentation.

Make an image responsive without stretching it

Keep the intrinsic attributes and apply proportional sizing in CSS:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
img {
  max-width: 100%;
  height: auto;
}

max-width: 100% lets the image shrink when its containing block is narrower than the source. height: auto derives the rendered height from the intrinsic ratio, so a 1200 × 800 image displayed at 600 pixels wide becomes 400 pixels high. The image will not be stretched or squashed.

Component-scoped CSS

Global rules may affect logos, icons, or other images that need different treatment. Scope the responsive rule to the component instead:

.article-body img {
  display: block;
  max-width: 100%;
  height: auto;
}

display: block removes the small inline baseline gap that can appear below images. It is optional for sizing, but useful when an image should occupy its own block.

When only CSS width is set

If you set a CSS width and leave CSS height as auto, the user agent preserves the intrinsic aspect ratio. The safer explicit pattern is still width: 100%; height: auto or max-width: 100%; height: auto, combined with HTML width and height attributes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a deliberate ratio and cropping when the design requires it

Some cards, hero areas, and galleries must occupy a fixed ratio even when source files differ. Use the CSS aspect-ratio property, then choose how the image fills that box with object-fit:

.card-media {
  width: 100%;
  aspect-ratio: 16 / 9;
  object-fit: cover;
}

.card-media img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

With object-fit: cover, the image fills the 16:9 box and crops overflow. Use object-fit: contain when the entire image must remain visible; this can leave empty space inside the box. A deliberate component ratio is different from the image’s natural ratio, so expect cropping or letterboxing when they do not match.

aspect-ratio is most useful when at least one dimension is automatic. You can still provide intrinsic HTML dimensions so the browser knows the source ratio while the component’s CSS establishes its design box.

Serve the right file with srcset and sizes

Dimensions solve layout reservation; they do not by themselves solve bandwidth. When you have several versions of an image, let the browser select an appropriate candidate:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<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">
  • srcset lists candidate files and their intrinsic widths using w descriptors.
  • sizes describes the rendered CSS width at different viewport conditions. In this example, the image can use the full viewport up to 600 pixels, and is expected to occupy about 800 pixels above that breakpoint.
  • src remains a fallback and should point to a usable candidate.

The HTML width and height values should describe the same aspect ratio as the candidates. In the example, 1600 × 1067 is approximately 3:2, matching the 400-, 800-, and 1600-pixel versions. If one candidate is cropped to a different ratio, use markup and dimensions that accurately represent the resource set you are serving.

Art direction versus resolution switching

srcset with width descriptors is resolution switching: alternate files show the same composition at different sizes. If mobile needs a different crop or composition, use a <picture> element with separate sources. Give each delivered image an accurate ratio and retain a meaningful alt on the fallback <img>.

Accessibility: write the right alt text

The dimensions do not describe the image to a screen reader. Provide concise alternative text that conveys the image’s purpose:

<img src="team.jpg" width="1200" height="800" alt="The product team at its 2026 planning meeting">

For a purely decorative image, use an empty value:

<img src="divider.svg" width="1200" height="40" alt="">

An empty alt tells assistive technology to skip the image. Do not omit alt on a content image; omitting it can cause a screen reader to announce the file name or URL instead of useful context.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Lazy loading and below-the-fold images

You can ask the browser to defer off-screen images:

<img
  src="gallery-1.jpg"
  width="1600"
  height="1067"
  loading="eager"
  alt="A mountain trail in autumn">

Lazy loading increases the importance of intrinsic dimensions. The browser may not fetch the file until it is near the viewport, but it still needs the reserved ratio to avoid a layout shift. Do not lazy-load the primary above-the-fold image by default; it is usually better to let that image start immediately and consider fetchpriority="high" only when you have a measured reason.

Choosing the correct approach

Need HTML CSS Result
Reserve natural image space width and height with intrinsic pixels None required Browser knows the ratio before download
Fluid image that never exceeds its container Keep intrinsic attributes max-width: 100%; height: auto Proportional shrinkage
Fixed design ratio Keep accurate source dimensions aspect-ratio plus object-fit Controlled box, crop or contain behavior
Different files for different screens srcset and sizes Responsive layout rules Browser selects an efficient candidate

Common mistakes and how to fix them

Adding units to HTML attributes

Symptom: validation warnings or dimensions that do not behave as expected. Fix: write width="1200", not width="1200px"; put px, rem, percentages, or viewport units in CSS.

Setting a fixed height with a fluid width

Symptom: faces and objects look stretched. Fix: replace the fixed CSS height with height: auto, or use a deliberate aspect-ratio and an intentional object-fit mode.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Using the wrong intrinsic dimensions

Symptom: a blank gap is too tall or too short, followed by a jump when the image arrives. Fix: inspect the actual file metadata and update both attributes. For a transformed or cropped derivative, use that derivative’s dimensions, not the original upload’s.

Omitting dimensions on lazy-loaded content

Symptom: text moves when scrolling reaches an image. Fix: add accurate width and height attributes, or reserve the known ratio with CSS.

Confusing display size with source size

Symptom: changing an HTML attribute does not produce the visual width you expected. Fix: use CSS for rendered size. The attributes describe intrinsic geometry and early layout reservation; CSS determines the final box.

Debug an image that looks wrong

  1. Inspect the element. In browser developer tools, check the rendered dimensions, the HTML attributes, and the active CSS rules.
  2. Check the natural size. In the console, select the image and evaluate $0.naturalWidth and $0.naturalHeight. Compare those values with the intended source and ratio.
  3. Look for competing rules. A later selector, inline style, flex or grid constraint, or a global img { height: ... } rule may override your responsive rule.
  4. Check object fitting. If the box is correct but content is cropped, inspect object-fit and object-position; cropping may be intentional rather than a sizing error.
  5. Test narrow and wide viewports. Confirm that max-width: 100% prevents overflow and that the ratio remains stable at breakpoints.
  6. Test with the network panel. A 404, blocked request, unsupported format, or server response with the wrong content type can look like a dimension problem but requires fixing the asset delivery.

Validate a production image component

  • Both HTML dimensions are present and are unitless integers.
  • The dimensions match the delivered file’s intrinsic ratio.
  • Responsive images use max-width: 100%; height: auto unless a fixed component ratio is intentional.
  • srcset candidates and sizes describe the actual layout.
  • Every meaningful image has useful alt text; decorative images use alt="".
  • Lazy-loaded images reserve space before their requests begin.
  • Any crop is explicit through object-fit and does not hide important content.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you need a rendered screenshot of an HTML page to verify image sizing across a URL, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

One GET request returns PNG, JPEG, WebP, or PDF. The API supports full-page captures with lazy images loaded, CSS-selector element capture, custom CSS and JavaScript, viewport and device presets, dark mode, retina scale, wait conditions, request blocking, cookies and headers, geolocation and timezone, transparent backgrounds, resizing, caching with a chosen TTL, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, and a usage API. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Best Value
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

See the ScreenshotNeo documentation for all parameters. Replace the target URL below with your page:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is included on every plan, and annual billing provides two months free. Create a free ScreenshotNeo account to begin.

Frequently Asked Questions

Can I specify percentages in an HTML width attribute?

No. HTML image width and height attributes use unitless integer values. Put percentage, pixel, or other CSS units in a stylesheet instead.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do width and height change the downloaded image’s quality?

No. They describe intrinsic geometry and reserve layout space. Use CSS, responsive sources, or an image transformation service to control rendered size and bytes transferred.

Should decorative images have dimensions?

Yes. Keep accurate dimensions to reserve layout space, and set alt="" so assistive technology treats the image as decorative.

Why is my image cropped after adding aspect-ratio?

A fixed ratio creates a design box. If it differs from the source ratio, object-fit: cover crops the overflow. Use contain or a matching ratio when the full image must remain visible.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.