Gregory Magarshak
Gregory Magarshak

Reputation: 2119

How does getBoundingClientRect() interact with box-sizing?

So jQuery's .width() always returns the clientWidth, regardless of what it is. But if you want subpixel accuracy, you have to opt for getBoundingClientRect.

My question is a cross-browser question. Say I want to use getBoundingClientRects() or getBoundingClientRect(). In all major browsers used today (i.e. those used by at least 95% of people), do they return the width of the client area, i.e. essentially the element.clientWidth regardless of the box-sizing? Or do I have to subtract the padding if the element has box-sizing: border-box ? For that matter, how do I get subpixel values for padding and margins?

I am looking for an answer that speaks about the behavior of major browsers in use today.

Upvotes: 2

Views: 2048

Answers (1)

Kaiido
Kaiido

Reputation: 136678

From MDN : emphasize mine

The returned value is a DOMRect object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

So this method does return the border-boxes, and thus should not be influenced by the box-sizing attribute whatsoever.

So width and height values of the returned DOMRect will be the same as the ones returned by offsetWidth and offsetHeight properties, except that these later are rounded.


I can only say that this is what specs ask UAs to implement. I don't know how the different implementations did differ. IIRC, some early implementations of getBoundingClientRect did round width and height values too, but I have no idea of the browser usage of such buggy implementations.

Upvotes: 1

Related Questions