Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't getComputedStyle take into account margin collapsing?

Concerning in-browser Javascript, the window.getComputedStyle() method is supposed to give the final used values of the CSS properties applied to an element. According to the MDN documentation, that means “after all calculations have been performed”.

However, it seems that “all calculations” does not include margin collapsing. In Firefox and Chrome (at least), the instruction getComputedStyle().marginBottom returns the computed value before any margin collapsing has been calculated.

For instance, consider the following element:

<div style="margin: 10px 0 15px 0"></div>

Its top and bottom margins will be collapsed because (roughly) its content height is zero (cf. the W3C CSS2 Recommendation). The CSSOM methods will return these values:

getComputedStyle().marginTop → 10px
getComputedStyle().marginBottom → 15px
getBoundingClientRect().top → {top of margin box} + marginTop
getBoundingClientRect().bottom → idem top

But, due to margin collapsing, the layout shows a margin of 10px before the bounding client rectangle, and a margin of 5px after, i.e. max(0, marginBottom - marginTop).

Why doesn't getComputedStyle().marginBottom return directly 5px, the real used value “after all calculations have been performed”, instead of the specified 15px? Is this a W3C-recommended behavior? (I haven't seen anything about this in the w3.org docs.)

Is this a bug or a feature?

like image 840
Martin Bouladour Avatar asked Mar 18 '26 00:03

Martin Bouladour


1 Answers

There's a distinction between computed and used values. Furthermore, getComputedStyle() returns resolved values, "which may either be the computed value or the used value". MDN reference.

As for the practical value of the many calculation states, I don't know any.

like image 132
Minh Nghĩa Avatar answered Mar 20 '26 12:03

Minh Nghĩa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!