Jamie Taylor
Jamie Taylor

Reputation: 3530

find the height of a div and change the current div height to match

I'm trying to make a div the same height as the parent (if the parent is larger) or make the parent the same height as the current div (if the current div is larger)

Here's what i've got so far

$(this).parents().find('.address').slideToggle(function() {
    $(this).parent().height($(this).parent().find('.address').height())
})

It makes the parent the height of the current div (but in my current case the parent is larger than the current div

Any ideas?

Thanks

Jamie

Upvotes: 0

Views: 1209

Answers (2)

Adeel
Adeel

Reputation: 19238

Check the solution here

Sample Html:

<div id="parent" style="height:500px;border:1px solid #000000">
    <div id="child" style="height:300px;border:1px solid #000000">child</div>
</div>

Javascript:

 jQuery(document).ready(function() {
                 var $parentDiv = $('#parent');
                 var $childDiv = $('#child');       
                 if($childDiv.height() > $parentDiv.height())  
                    $childDiv.css('height', $parentDiv.height());               
                 else
                     $parentDiv.css('height', $childDiv.height()); 

        });

Upvotes: 1

fcalderan
fcalderan

Reputation:

your script is not really readable (and is not really performing) but you could just read the height of the two elements and then set the height to the shorter one

var child = $(...),
    parent = child.closest(...),

    h = Math.max(child.height(), parent.height()),
    e = (child.height() > parent.height())? parent : child;
    e.css('height', h + 'px');

Upvotes: 0

Related Questions