HTML DOM Element offsetWidth attribute

Definition and Usage

offsetWidth The attribute returns the visible width of the element (in pixels), including padding, border, and scrollbar, but not including margin.

offsetWidth The attribute is read-only.

See also:CSS Box Model Tutorial

offsetParent

All block-level elements report offsets relative to the offset parent:

  • offsetTop
  • offsetLeft
  • offsetWidth
  • offsetHeight

Offset parent refers to the nearest ancestor with a non-static position.

If there is no offset parent, the offset is relative to the main body of the document.

See also:

offsetHeight attribute

offsetParent attribute

offsetTop attribute

offsetLeft attribute

clientTop attribute

clientLeft attribute

clientWidth attribute

clientHeight attribute

Instance

Example 1

Get the height and width of "myDIV", including padding and border:

const elmnt = document.getElementById("myDIV");
let text = "High with padding and border: " + elmnt.offsetHeight + "px<br>";
text += "Width with padding and border: " + elmnt.offsetWidth + "px";

亲自试一试

例子 2

clientHeight/clientWidth 与 offsetHeight/offsetWidth 的区别

不带滚动条:

const elmnt = document.getElementById("myDIV");
let text = "";
text += "Height with padding: " + elmnt.clientHeight + "px
"; text += "Height with padding and border: " + elmnt.offsetHeight + "px
"; text += "Width with padding: " + elmnt.clientWidth + "px
"; text += "Width with padding and border: " + elmnt.offsetWidth + "px";

亲自试一试

带滚动条:

const elmnt = document.getElementById("myDIV");
let text = "";
text += "Height with padding: " + elmnt.clientHeight + "px
"; text += "Height with padding, border and scrollbar: " + elmnt.offsetHeight + "px
"; text += "Width with padding: " + elmnt.clientWidth + "px
"; text += "Width with padding, border and scrollbar: " + elmnt.offsetWidth + "px";

亲自试一试

语法

element.offsetWidth

返回值

类型 描述
数字 元素的可视宽度(以像素计),包括内边距、边框和滚动条。

浏览器支持

所有浏览器都支持 element.offsetWidth

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
支持 支持 支持 支持 支持 支持