Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Inline width and height: `style.width` and `style.height`

Use `element.style.width` and `element.style.height` to read, set, and remove inline CSS declarations. Reading a declaration is not the same as measuring the element.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

element.style.width
 element.style.height
 element.style.width = cssWidth
 element.style.height = cssHeight
 element.style.width = ""
 element.style.height = ""

HTMLElement.style width/height refers to element.style.width and element.style.height. They read and write CSS declarations in the HTML element’s style attribute, not its width or height HTML attributes. element.style gives you a live declaration object, not a snapshot. Each property returns CSS text or "" if there is no inline declaration, even when a stylesheet supplies a value.

Assign strings such as "120px", "50%", or "auto". Include px when you mean pixels: the API does not add a unit to a number. An invalid value such as "invalid" leaves the existing declaration unchanged. Assigning "" removes the inline declaration and lets the cascade choose the value; assigning "auto" sets a declaration instead.

An inline declaration does not guarantee the final size. The cascade, layout, and constraints such as max-width can affect it. These properties do not apply to non-replaced inline elements such as an ordinary span. box-sizing determines whether the specified size targets the content box (content-box) or includes padding and borders (border-box).

For an element participating in layout, read getComputedStyle(element).width or .height for the resolved CSS value as text. For bounding rectangle dimensions in CSS pixels, call element.getBoundingClientRect() and read its numeric width and height. The rectangle includes padding and borders and reflects CSS transforms. These are browser APIs, not part of ECMAScript 2024; you need an environment with a DOM.

Examples

<!doctype html>
<meta charset="utf-8">
<title>Inline width and height</title>
<script>
  const element = document.createElement("div");
  const style = element.style;
  const log = () => console.log(JSON.stringify([style.width, style.height]));

  log();
  element.style.width = "50%";
  element.style.height = "80px";
  log();

  element.style.width = "invalid";
  log();

  element.style.width = "";
  element.style.height = "auto";
  log();
</script>

Result

["",""]
["50%","80px"]
["50%","80px"]
["","auto"]

Save the example as an `.html` file, open it in a browser, and check the developer console. The `div` is never attached to the document, so the four lines show declarations, not layout measurements.

Related lessons

  • JavaScript · Lesson 12 · Advanced · Version: 4

Sources