Development – Leet 4 Life

Software Development Code Samples and More

Skip to: Content | Sidebar | Footer

JQuery Dynamic Height and Width

28 November, 2012 | jQuery | By: Michael Adams

I was working on a few pages where I wanted the content to automatically fill the height/width regardless of browser size. I set my DIV tag with a id of “Content” and then created the following JQuery automatically scale the DIV tag to the appropriate height and width. I only have one DIV tag that required dynamic height and width so I was able to just subtract the height and width of the other elements on the page. Replace N with the height/width of the other elements on the page.
The JQuery:

$(function () {
   $('#content').css({ 'height': (($(window).height()) - N) + 'px' });
   $('#content').css({ 'width': (($(window).width()) - N) + 'px' });
   $(window).resize(function () {
      $('#content').css({ 'height': (($(window).height()) - N) + 'px' });
      $('#content').css({ 'width': (($(window).width()) - N) + 'px' });
   });
});

JQuery Break down:

$(window).height()

I use $(window).height() to get the height of the browser window

(($(window).height()) - N)

then subtract the height of the other static elements in my page

$('#content').css({ 'height': (($(window).height()) - N) + 'px' });

Lastly we assign it to the height style property of my DIV tag with the id of Content.
The width functionality is similar except we use $(window).width() instead.
You’ll notice we also cover on window resize by including:

$(window).resize(function () {
      $('#content').css({ 'height': (($(window).height()) - N) + 'px' });
      $('#content').css({ 'width': (($(window).width()) - N) + 'px' });
});

Code Originally posted Here.

Write a comment