Using jquery to calculate height of an element that contains another with a margin

I have to calculate the size of a div. Jquery has a handy function for that, which is outerHeight(). That gives you the element's size, and if you want to include the margins, you call outerHeight(true).

But. If the inner elements have a margin, the outer element's size doesn't change. Even though the inner one is still considered to be completely within. Here's an example of what I mean.

The outer div has an outerHeight of 18, and the inner one has an outerHeight of 218, which is 18 of the text, and two 100px margins.

I can't keep track of all the things that will be inside of my final div. How can I measure its actual height, including the margins of content contained within?

Answers


It's a little bit hacky way, but you can add

#container {
    border: 1px solid transparent;
}

This will force the container to get the correct height.

document.write('container height= ' + $("#container").outerHeight(true) + '<br>');
document.write('stuff height= ' + $("#stuff").outerHeight(true));
#stuff {
  margin: 100px;
}
#container {
  border: 1px solid transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <p id="stuff">
    lorem ipsum and so on
  </p>
</div>

I would consider your css a bad practice and change it. E.g. you could wrap the inner div and give the wrapper a padding instead of the margin.

HTML

<div id="container">
  <div id="wrapper">
    <p id="stuff">
      lorem ipsum and so on
    </p>
  </div>
</div>

CSS

#wrapper {
  padding: 100px;
}
#stuff {
  margin: 0;
}

I updated your example: https://jsfiddle.net/h8uvyx1w/2/

Or perhaps you don't need the wrapper, if you can change the inner divs margin to padding, depending on your needs.


Need Your Help

How to check effectively if one path is a child of another path in C#?

c# .net windows path

I am trying to determine if one path is a child of another path.

Count how many char in array numbers

php arrays strlen

I've an array got with preg_match_all.