Understanding offsetWidth and clientWidth when css border-box is active
Asked Answered
M

1

6

I come from this question: Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

I understand that this is the case for the standard box model, is that right?

But what happens when you have something like this:

*{
  box-sizing: border-box;
}

Are offsetWidth and clientWidth equal now? Does this happen always with this rule?

And what about padding-box?

Mineral answered 21/5, 2015 at 16:55 Comment(0)
C
7

Try it out yourself: http://codepen.io/anon/pen/WvojWw

By default it is set to box-sizing: border-box but just change that in the styles to get different results.

It calculates offsetWidth and clientWidth for you when you click the button.


Offset width is equal to all but margins, so if you use border-box, you're just going to get the width you specify.

And client width is equal to all but margins and borders, so you're just going to get your specified width - borders when you use border-box.

offsetWidth

without border-box:

offsetWidth = width + padding + border

with border-box:

offsetWidth = width

clientWidth

without border-box:

clientWidth = width + padding

with border-box:

clientWidth = width - border

Childers answered 26/5, 2015 at 9:4 Comment(3)
So you say that the box-sizing doesn't affect at all, they are always the same while border is 0, is that it?Mineral
@Mineral Border being 0 is not enough, but if the border and padding are both 0, then the box-sizing does not change the end result. But if there is any border or padding, then the end result is different. Effectively, if you use border-box, you will get what you specify as width, but without it you will get width + padding + border.Childers
@Mineral I added a brief summary to my answer about how offsetWidth and clientWidth would turn out.Childers

© 2022 - 2024 — McMap. All rights reserved.