HTML DOM offsetWidth Property

元素对象参考手册Element Object

Example

Get the width of a div element, including padding and border:

var elmnt = document.getElementById("myDIV"); var txt = "Height of a div element, including padding and border:" + elmnt.offsetHeight + "px<br>"; txt += "Width of a div element, including padding and border:" + elmnt.offsetWidth + "px";

Try it yourself »

Definition and Usage

The offsetWidth property is a read-only property that returns the pixel width of the element. The width includes padding and border, but does not include margin. It is an integer, in pixels (px).

Typically, an element's offsetWidth is a measure of the element's CSS width, including the element's border, padding, and the element's horizontal scrollbar (if present and rendered), and does not include:beforeor:afterthe width of pseudo-class elements, etc.

For the document's body object, it includes the element's total linear content height instead of the CSS width. The width of the content extending downward from floating elements is ignored.

If the element is hidden (for example: the element or one of the element's ancestors' element'sstyle.displayis set tonone), it returns 0.

Note:To understand this property, refer toCSS Box Model。

Tip:This property is usually used with theoffsetHeightproperty.

Tip:Use the clientHeightandclientWidthproperty to return the element's visible height and width, including only padding.

Tip:To add a scrollbar to an element, you can use theoverflowproperty.

This is a read-only property.


Browser Support

Property
offsetWidth Yes Yes Yes Yes Yes

Syntax

element. offsetWidth 

Technical Details

Return Value: Returns an integer representing the pixel width of the element.

More Examples

Example

The following example demonstrates the difference between the clientHeight/clientWidth and offsetHeight/offsetWidth properties:

var elmnt = document.getElementById("myDIV"); var txt = ""; txt += "Height including padding:" + elmnt.clientHeight + "px<br>"; txt += "Height including padding and border:" + elmnt.offsetHeight + "px<br>"; txt += "Width including padding:" + elmnt.clientWidth + "px<br>"; txt += "Width including padding and border:" + elmnt.offsetWidth + "px";

Try it yourself »

Example

The following example demonstrates the difference between the clientHeight/clientWidth and offsetHeight/offsetWidth properties after adding a scrollbar to the element:

var elmnt = document.getElementById("myDIV"); var txt = ""; txt += "<b>div's style information:</b><br>"; txt += "Height including padding:" + elmnt.clientHeight + "px<br>"; txt += "Height including padding, border, and scrollbar:" + elmnt.offsetHeight + "px<br>"; txt += "Width including padding:" + elmnt.clientWidth + "px<br>"; txt += "Width including padding, border, and scrollbar:" + elmnt.offsetWidth + "px";

Try it yourself »


元素对象参考手册Element Object

Other Extensions