Set a Container to the Window Height with jQuery

A common issue with CSS is finding the best way to set an element, such as a div, to stretch from the top of the screen, to the bottom of the screen. You can do this with positioning. Sometimes, though, you want the div to start from after the banner, navigation, or something else. This creates some additional variables. You also need to account for what happens if someone resizes the screen.

I attacked this issue with jQuery, so you’ll need to have it already installed on your site.

Simple Top to the Bottom of the Screen

$(function(){
  // SET THE DIV TO THE WINDOW HEIGHT
  $('.div_class').css({'height':($(window).height())+'px'});
  // RESIZE THE HEIGHT IF THE WINDOW IS RESIZED
  $(window).resize(function(){
    $('.div_class').css({'height':($(window).height())+'px'});
  });
});

That’s it! Fairly simple and easy to do. Depending on what you’re doing, you may want to use CSS positioning to achieve this effect.

It only gets a little more complex when you need to subtract a header from the size of the div.

Subtract the Height of a Banner

You might think that this would involve a lot of work. Not really. You just need to know how tall you banner and/or footer is. Let’s say that your banner is 150px tall. Your jQuery would look something more like this.

$('.div_class').css({'height':(($(window).height())-150)+'px'});

Practical Uses

I use this technique to set the height of my content, with a fixed, transparent footer and a standard banner. This causes the content to fit my window and scroll without losing the banner or the footer. I do have some special rules that kick in for minimum heights and widths so that everything displays well on mobile devices.

How will you use this little snippet of jQuery?

Published by

Tim Bunch

Tim Bunch is a Web Developer from Boise, Idaho. As a web standards fanatic, he passionately pursues best practices. He also actively engages people on a wide range of topics in a variety of social media networks. Tim is also an avid Wordpress developer, music maker, coffee drinker, and child raiser. @timbunch

Leave a Reply

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