user2758988
user2758988

Reputation: 139

How to Set Dynamic Height jQuery

I have multiple parent divs with the same class names, one is parent div and other is child div.

 <div class="container" style="height:150px; width:50%;">
    <div class="overlay"></div>
 </div>

 <div class="container" style="height:250px; width:50%;">
    <div class="overlay"></div>
 </div>


 <div class="container" style="height:350px; width:50%;">
    <div class="overlay"></div>
 </div>

I want to set overlay div height equals to the container div height, problem i'm facing is that every container div has different height and i'm unable to find out how to set each overlay div height equals to it's parent container div height.

I'm using following jquery code to set overlay height for each

$(".container").each(function(){
    $(".overlay").height($(".container").height());
});

Above code get the height of only first container and set all overlay divs height to first container. I mean it set height:150px in all overlay divs and i want to set overlay div height equals to its parent container div.

<div class="container" style="height:150px; width:50%;">
    <div class="overlay" style="height:150px;"></div>
 </div>

 <div class="container" style="height:250px; width:50%;">
    <div class="overlay" style="height:150px;"></div>
 </div>


 <div class="container" style="height:350px; width:50%;">
    <div class="overlay" style="height:150px;"></div>
 </div>

Upvotes: 0

Views: 91

Answers (3)

Rick Hitchcock
Rick Hitchcock

Reputation: 35680

Set overlay height to 100% in style sheet:

.overlay {
  height: 100%;
}

Upvotes: 0

Banana
Banana

Reputation: 7484

the selector $(".container").height() returns a list of containers, and takes the height of the first one from the list.
therefore, when you set $(".overlay").height($(".container").height()), you set all child elements to the height of the first container.

you need to iterate through all child containers, and set their height respective to their container. it can be achieved using the $(this) keyword which represents the current child element, and by taking its .parent() which will return its respective container parent element.

$(".overlay").each(function(){
    $(this).height($(this).parent().height());
});

Upvotes: 0

Bardh Lohaj
Bardh Lohaj

Reputation: 1410

You can do it like this:

$(".overlay").each(function(){
    $(this).height($(this).parent().height());
});

Upvotes: 1

Related Questions