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,
});
});
Written by Jake Chapman
Related protips
8 Responses
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.
@janvl You are right
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
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.
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..
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.
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 ?
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