Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

HTML width attribute

The width attribute specifies the width of supported HTML elements. It takes a non-negative integer without a unit. On canvas, it controls the bitmap width, not merely the display size set by CSS.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

width="<non-negative integer>"

width is not a global attribute. It specifies the horizontal dimension in CSS pixels on img, iframe, embed, object, video, input with type="image", and source whose parent is picture. Its value is a non-negative integer, such as width="240", without px or %.

Dimension attributes are rendering hints; CSS can change the display size. They are not intended to stretch images: a width and height pair should preserve the natural aspect ratio within the standard's rounding tolerance. picture itself does not support width; its img displays the image, and dimensions can also be supplied on the relevant source elements.

On canvas, the width attribute controls the bitmap width. A missing value or a parsing error gives the default 300; the default height is 150. Changing only the CSS size scales the presentation without changing bitmap dimensions. Setting width with a 2D context clears the bitmap and resets drawing state, even when assigning the existing value.

The example separates the two sizes: the bitmap is 240 × 120, but it is displayed at 480 × 240 CSS pixels.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>width attribute</title>
<canvas id="drawing" width="240" height="120" style="width: 480px; height: 240px">Canvas demonstration</canvas>
<pre id="result"></pre>
<script>
  const canvas = document.getElementById('drawing');
  document.getElementById('result').textContent =
    `Bitmap: ${canvas.width} x ${canvas.height}\n` +
    `CSS width: ${getComputedStyle(canvas).width}`;
</script>
</html>

Result

Bitmap: 240 x 120
CSS width: 480px

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources