Leanne
Leanne

Reputation: 83

Set parent div to absolute child div height

I have multiple .parent divs each containing an absolute positioned .child div. I managed to extend the height of .parent to the height of the .child using the following code.

However, this makes every .parent the same height, which is the height of the largest .child in the site. I need each .parent to only extend it's height to their own .child and no larger.

Any suggestions?

function parentHeight(){
     divHeight = $('.parent .child').height();
     $('.parent').css({'height' : divHeight});
 }
 parentHeight();

Upvotes: 1

Views: 89

Answers (1)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

Try following using jQuery.each

function parentHeight(){
    $('.parent .child').each((i,el) => {
      $(el).closest(".parent").css({'height' : $(el).height()})
    });
 }
 parentHeight();
.parent {
  background-color: blue;
  width: 100px;
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="parent"><div class="child" style="height:200px">A</div></div>
<div class="parent"><div class="child" style="height:300px">B</div></div>
<div class="parent"><div class="child" style="height:400px">C</div></div>

Upvotes: 1

Related Questions