HTML element height including margin and children's margin

I can get the height of an element with

HTMLElement.offsetHeight

but this is without margin. I can get the height including margin using the function from Find element height, including margin.

But if I have a child element with a bigger margin than parent that function does not give me the height I want. How to I get the height of an element including margin of both the element and child elements?

Related example:

HTML:

<div id="outer">
  <div id="inner">
    <p>
      New York
    </p>
  </div>
</div>

CSS:

#inner {
  padding-top: 1px;
  padding-bottom: 1px;
}

#inner p {
  margin-top: 21px;
  margin-bottom: 100px;
}

If I use outer.offsetHeight the height is including the margin of the p-element. But if I remove the 1px padding of inner, then outer.offsetHeight disregards the margin of the p-element. Why?

Upvotes: 4

Views: 2278

Answers (2)

likle
likle

Reputation: 1797

The reason for that is "margin collapsing". Basically, it combines the two margins of your blocks into one. In your case it only occurs if there is no padding.

The specification is a bit hard to read in my opinion, so you probably find MDN easier!

Upvotes: 3

Charles Cavalcante
Charles Cavalcante

Reputation: 1608

Change the #inner display to flex:

#inner {
  display: flex;
}

JSFiddle: https://jsfiddle.net/charlesartbr/gs3orv59/12/

Upvotes: 2

Related Questions