Last Updated: September 09, 2019
·
29.29K
· imjakechapman

Div Full Width/Height of viewport

// global vars
var winWidth = $(window).width();
var winHeight = $(window).height();

// set initial div height / width
$('div').css({
    'width': winWidth,
'height': winHeight,
});

// make sure div stays full width/height on resize
$(window).resize(function(){
    $('div').css({
    'width': winWidth,
    'height': winHeight,
});
});

8 Responses
Add your response

couldn't you achieve the same result with absolute positioning and height/width: 100% ?

div{ position: absolute; width: 100%; height: 100%; top: 0; left: 0; } </code>

no need for javascript this way.

over 1 year ago ·

@janvl You are right

over 1 year ago ·

Hey guys, you are absolutely correct.

I was messing around with Javascript awhile back trying to come up with a js only solution. Dumb, I know. But none the less you are right. :)

But this has other uses as far as trying to set the height/width of an element on the window.resize function

over 1 year ago ·

I used this method when fitting the width/ height of a slider element as same as width/ height of viewport. It would like a sectional area that fits the viewport and not overflowing from viewport edge before we scroll down the page.

over 1 year ago ·

i used this code to make a mega menu in bootstrap where the dropdown element is already positioned absolute,.. & styling its width to a 100% via CSS didn't work..

over 1 year ago ·

This is actually a great solution, as pages with content larger than the viewport would cause an absolutely positioned element to stretch beyond the visible area. I had issues with this on a client's site where their logo was not centered on the page (for a splash overlay with fadeOut) due to the content being taller than the viewport.

over 1 year ago ·

What if i want 3 or more divs with 100% height and width of the page for every viewport, so when you scroll down to another div it will have 100% width and height. Can i do it with this ?

over 1 year ago ·

Hi Everyone,

I need full height and window re size function.. As like upwork chat page so could you tell me plz how can i fix that issue with js and css :) http://screencast.com/t/bJikvDUFFjws

Thanks

over 1 year ago ·