Why doesn't getComputedStyle take into account margin collapsing?
Asked Answered
U

2

12

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?

Ume answered 1/5, 2013 at 13:8 Comment(0)
S
1

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.

Suffruticose answered 8/12, 2021 at 8:30 Comment(0)
E
0

I don't see all of your code, but I think that the function name is actually, "getComputedStyle," with a "u".

A typo? Could it be that easy? You wouldn't be the first — myself included.

Hoping this helps.

Eaton answered 12/5, 2014 at 19:14 Comment(2)
Yes that was a typo. ThanksUme
But the question still stands ;-)Ume

© 2022 - 2024 — McMap. All rights reserved.