The HTML width attribute
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
widthand height on images and iframes to reserve space and prevent layout shift. - Use a unitless pixel number —
width="640", notwidth="640px". - For responsive images, add CSS
max-width: 100%; height: autoon 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?
Why should I set width and height on images?
Do I include px in the width attribute?
width="640".Does CSS width override the attribute?
width: 100% overrides the attribute's pixel value.