Question

I want to make a the height of the child div a percentage of a grandparent using jquery.

grandparent
   parent
       child

I want the child to be a percentage in height of its grandparent so it is responsive to the viewport.

No correct solution

OTHER TIPS

Erik, you haven't been very specific.

For example, if 'parent' is a fixed percentage height of 'grandparent' then it is simple maths to set the percentage height of child in CSS, no JS required.

Otherwise, with jQuery if you want child to be 25% height of grandparent:

var grandparent_height = $('#grandparent').height();
$('#child').height( grandparent_height * 0.25 );

Is there more to your question than that?

If you are looking to set the size of child relative to the viewport and you are happy working with modern browsers only, then you can use the CSS vh unit (1vh is 1% of the viewport height), and set

#child {
    height: 25vh;
}

Different browsers can return different results when measuring viewport size. Here is a good resource (and javascript library) about the different browser treatment: http://verge.airve.com/ )

if this is your code:

<div>
  <div>
    <div class="child">
    </div>
  </div>
</div>

you can probably do something like:

var percentValue; // Set your percent here
var grandparentHeight = $('.child').parent().parent().height();
$('.child').css({'height' : grandparentHeight * percentValue});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top