Luta V
Luta V

Reputation: 9

Manipulate div heights with relation to window height

I have several divs i.e

<div class="div_1"></div>
<div class="div_2"></div>
<div class="div_3"></div>

After getting window height by

windowHeight = window.innerHeight;

I want to manipulate the div height to be a proportion of the window height for example div_1 should be 30%, div_2 should be 45% of window height etc. I need to do this in javascript / jquery.

Upvotes: 0

Views: 72

Answers (3)

Luta V
Luta V

Reputation: 9

I've manipulated @void's answer to get an answer that I expected. The code is

$('.div_1').height(windowHeight*30/1400+"em");

I divided the windowHeight by 1400 instead 100 because the body font is 14px, for changing it from px to em.

Upvotes: 0

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

As a alternative using jquery & data attribute

<div id="container">
  <div class="div_1" data-percent="30">Div1</div>
  <div class="div_2" data-percent="40">Div2</div>
  <div class="div_3" data-percent="30">Div3</div>
</div>

<script>
  $(window).resize(function(){
  var height = window.innerHeight;
   console.log('resised',height)
      $('#container>div').each(function(){
         $(this).height(height*parseInt($(this).data('percent'))/100);
        console.log($(this).height(),height*parseInt($(this).data('percent'))/100);
      });
    })
</script>

Upvotes: 0

void
void

Reputation: 36703

You can simply use CSS

.div_1 {height:30vh;}

This will set height equal to 30% of the height of viewport. vh is the height of viewport.

It is partially supported in IE > 8 and other then that not supported in Opera, else where it is completely supported. http://caniuse.com/#feat=viewport-units

To do it in jQuery

$('.div_1').css("height", $(document).height()*30/100+"px"); // Will set its height equal to 30% of that of document.

Upvotes: 1

Related Questions