Home > Blockchain >  How to detect child div's height exceeding parent div's height
How to detect child div's height exceeding parent div's height

Time:10-27

I have a div A, which contains div B, which contains div C, which contains div D, where div A has a default height of 40px. It's something like below.

<div id='A' style="height: 40px">
  <div id='B'>
     <div id='C'>
         <div id='D'></div>
     </div>
  </div>
</div>

The thing is, div C is implemented in a way that it can dynamically change height. Therefore, it could exceed the default height of div A (40px) and cause some cosmetic issue.

What I want to achieve is to keep the height of div A as 40px as long as the height of any its child div doesn't exceed 40px. However, if the height of any its child div exceeds 40px, I want height of the child div to override div A's height. For example, when div C changes height to 80px, I want div A's height to be 80px.

I am wondering if I need to write a method to dynamically calculate the height of each child div and do something like getElementById('A').style.height = null if the child height returned is greater than 40px.

Is there a better or simpler way to do that?

CodePudding user response:

Try using 'min-height'.

 min-height: 40px;

CodePudding user response:

As per the my point you no need to check each child element height.

If you check B child element height is more than enough, because that is the parent for child element C and D

According to that, following JS code will provide you the solution

// get parent div #A 
var parentElement = document.getElementById('A'); 

// parent div #A initialHeight
var parentDivOffsetHeight = 40; // no need to mentionion px

// get child div #B offest height
var childDivOffsetHeight = document.getElementById('B').offsetHeight;

// check if child div height is greater than parent div or not
if(childDivOffsetHeight > parentDivOffsetHeight){
    //set child div height to parent div
    parentElement.style.height = childDivOffsetHeight 'px';
}

Related JS Fiddle: https://jsfiddle.net/katheer_mizal/3ouypevd/18/

To check element hights you can use following ways

clientHeight includes padding.

var clientHeight = document.getElementById('B').clientHeight;

offsetHeight includes padding, scrollBar and borders.

var offsetHeight = document.getElementById('B').offsetHeight;

.style.height equalent to $('#content').css('height'.

var offsetHeight = document.getElementById('B').style.height;
  • Related