References

Beginner-friendly references for web development, with live, editable examples.

The HTML width attribute

Attribute All modern browsers Updated
Quick answer

The HTML width attribute sets the intrinsic width of the element in CSS pixels. It is used on the <img>, <video>, <canvas>, <iframe>, <embed>, <object> and <input type="image"> elements.

Overview

The width attribute sets the rendered width of certain elements — <img>, <video>, <iframe>, <canvas>, <embed> and image inputs — as a number of CSS pixels (unitless, with no "px").

For images and iframes, the single most valuable reason to set width alongside height is preventing layout shift: when the browser knows the dimensions up front, it reserves the space before the resource loads, so the page does not jump. That directly improves the Cumulative Layout Shift metric.

The attribute sets the element's intrinsic size, but CSS wins for display — width: 100% in CSS overrides the attribute. The standard responsive pattern is to set the width/height attributes (for the aspect ratio) and then add max-width: 100%; height: auto in CSS so the image scales down fluidly.

Syntax

<img src="p.jpg" width="640" height="360" alt="">

Values

Value
A non-negative integer (pixels).

Best practices

  • Set width and height on images and iframes to reserve space and prevent layout shift.
  • Use a unitless pixel number — width="640", not width="640px".
  • For responsive images, add CSS max-width: 100%; height: auto on top of the attributes.
  • On a <canvas>, the attribute is the drawing resolution, separate from the CSS display size.

Frequently asked questions

What does the width attribute do?
It sets the rendered width of an element such as an image, video, iframe or canvas, in CSS pixels.
Why should I set width and height on images?
So the browser reserves the right space before the image loads, preventing layout shift.
Do I include px in the width attribute?
No. It takes a unitless number of pixels, e.g. width="640".
Does CSS width override the attribute?
Yes. CSS wins for display, so width: 100% overrides the attribute's pixel value.