Skip to content Skip to sidebar Skip to footer

Change Parent Div Height Depending On Child Absolute Div Height Using Javascript

Iam working on project where I cam across the situation like this. I need my parent div stretch its height depending on the child div. The parent height is fixed for 400px; #parent

Solution 1:

If you try to set the width of the parent div to 100%

#parent-div{
min-height:400px;
width:250px;             <-
background-color:#333;
position:relative;
}

To

#parent-div{
min-height:400px;
width:100%;
background-color:#333;
position:relative;
}

Hope that helps you!

Solution 2:

Add this javascript since you are using jquery:

$().ready(function(){
    ch = $('#child-div').height();
    $('#parent-div').css({
        height : ch + 50 + 'px'
    })
});

Demo : JSFiddle

Solution 3:

$(function(){
    var parent= $('#parent');
    var parentOffset = parent.offset();
    var bottom = 0; 
    parent.find('*').each(function() {
        var elem = $(this);
        var elemOffset = elem.offset();
        var elemBottom = elemOffset.top + elem.outerHeight(true) - parentOffset.top;
        if (elemBottom > bottom) {
            bottom = elemBottom;
        }
    });

    parent.css('min-height', bottom);

});

Post a Comment for "Change Parent Div Height Depending On Child Absolute Div Height Using Javascript"