Element height based on viewport height

Today I had to create a little landing page for one of our clients. one of the requirements was to have the landing page fill the screen no matter what height the viewport was. So this would fill the space up on a desktop, iPad for example.

I stumbled across a handy piece of jQquery that makes use of jQuery height element, below is the snippet:

function stretch_pc() {
var height = $(window).height();
var stretch = (80 * height) / 100;
thirtypc = parseInt(thirtypc) + 'px';

$(document).ready(function() {
$(window).bind('resize', stretch_pc);

This is essentially a function that is defining two variables height and stretch. The height variable is simply just finding the height of the windows viewport. By reading the jQuery documentation here

The difference between .css('height') and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element’s height needs to be used in a mathematical calculation.

The second variable stretch is going to be 80 percent of the viewport  * the height of the document and then divided by 100 to give us 80 percent of the viewport height. You may change 80 to match whatever you find sufficient, I opted for this as the height element does not take in to account any padding or margin, so you will get a bit of excess if you decide to have these in your css.

Lastly, after the function, the jquery will load on the document ready and initialise the function, making the ‘div’ height match the percentage defined in the function.

Further reading: jQuery Documentation

Source: link

Join the Conversation

1 Comment

  1. Pingback: jesse
Leave a comment

Your email address will not be published. Required fields are marked *