Home > Mobile >  Adjust child element height based on Parent height and Top position value value
Adjust child element height based on Parent height and Top position value value

Time:11-18

I am having parent with fixed height (400px) and child div height more than parent div height (400px - child div's top value) should be based on below conditions.

  • Parent div height - child div's top position value (Eg: 40px in this scenario)

So, Finally Child div height should be 360px (400px - child div's top value of -40px)

HTML:

<div class="parent">
    <div >
        Parent Height: <span id="parentHeight"></span><br>
        Distance from top: <span id="distanceFromTop"></span><br>
        Child Height: <span id="childHeight"></span><br>
    </div>
</div>

Script:

var __parentHeight = $('.parent').height();
var __distanceFromTop = $('.parent').offset().top - $('.child').offset().top;
var __finalHeight = parseInt(__parentHeight) - parseInt(__distanceFromTop);

$('#parentHeight').html(__parentHeight   'px');
$('#distanceFromTop').html(__distanceFromTop   'px');
$('#childHeight').html(__finalHeight   'px');

$('.child').css('height', __finalHeight   'px');

enter image description here

What I am getting is:

enter image description here

CodePudding user response:

Update your final height calculation like that => var __finalHeight = parseInt(__parentHeight) - parseInt(__distanceFromTop);

CodePudding user response:

you are setting position not margin or padding. to get top position pixel use $('.child').position().top; this will get you that 40px position top.

here is fiddle jsfiddle

  • Related