Style width attribute

Definition and Usage

width attribute to set or return the width of the element.

width The attribute is only valid for block-level elements or elements with absolute or fixed positioning. Overflowing content can be set using overflow attribute to handle.

Tip:Use height attribute Sets or returns the height of the element.

See also:

CSS Tutorial:Dimensione CSS

CSS Tutorial:Modello di riquadro CSS

CSS Reference Manual:width attribute

Example

Example 1

Set the width of the <button> element:

document.getElementById("myBtn").style.width = "300px";

Try it yourself

Example 2

Change the width of the <div> element:

document.getElementById("myDIV").style.width = "500px";

Try it yourself

Example 3

Change the height and width of the <img> element:

document.getElementById("myImg").style.height = "300px";
document.getElementById("myImg").style.width = "300px";

Try it yourself

Example 4

Return the width of the <img> element:

alert(document.getElementById("myImg").style.width);

Try it yourself

Syntax

Return width attribute:

object.style.width

Set width attribute:

object.style.width = "auto|length|%|initial|inherit"

Attribute value

Value Description
auto Browser sets the width. Default.
length Defines the width, by length unit.
% Defines the width of the parent element, by percentage.
initial Sets this property to its default value. See initial.
inherit Inherits this property from its parent element. See inherit.

Technical details

Default value: auto
Return value: A string that represents the width of the element.
CSS version: CSS1

Browser support

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Supporto Supporto Supporto Supporto Supporto