Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between style.width and offsetwidth in HTML?

I notice that offsetwidth is a slightly bigger number. Similarly for style.height and offsetheight.

like image 282
yeeen Avatar asked Nov 15 '11 07:11

yeeen


People also ask

What is offsetWidth HTML?

The HTMLElement. offsetWidth read-only property returns the layout width of an element as an integer. Typically, offsetWidth is a measurement in pixels of the element's CSS width, including any borders, padding, and vertical scrollbars (if rendered).

What is the difference between clientWidth and offsetWidth?

clientWidth is the inner width (ie. the space inside an element including padding but excluding borders and scrollbars) offsetWidth is the outer width (ie. the space occupied by the element, including padding and borders)

What is clientWidth and clientHeight?

Using clientWidth and clientHeight you're able to get the pixel dimensions of an HTML element. The dimensions are calculated using the dimensions of content inside the HTML element, along with the padding. Note: Borders, margins, or scrollbars (if present) are excluded when computing clientWidth and clientHeight.


1 Answers

offsetWidth returns computed element's width, while el.style.width just returns width property defined in element.style by javascript and does not reflect real element's dimensions.

This means that if you will try to get a width of the element by accessing el.style, you will probably get nothing (sample), even if the width was defined in your CSS. You will get the number only if it was defined in el.style by javascript.

Furthermore, offsetWidth gives you real width of your element, including padding and border if you use content-box css box model which is default value for box-sizing. So you can think about that like you set width of the contents of the element and padding/border go on top of that (sample).

If you are using border-box css box model, you set the total width of the element, including padding and border make the content area smaller (sample). So, in this case, offsetWidth and el.style.width would return exactly the same numbers (if el.style.width was previously set by javascript).

like image 135
sol0mka Avatar answered Oct 05 '22 03:10

sol0mka