DEV Community

Cover image for How to make a div the same height as the browser window
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

How to make a div the same height as the browser window

You might think that making a div element the same height as your browser would be as easy as this:

div {
    height: 100%;
}
Enter fullscreen mode Exit fullscreen mode

However, it is unfortunately not. If you're wondering why height: 100%; doesn't work to make an element the full height of the screen, it's because a height has to be defined to use percentages in CSS. Since body tags have no predefined heights, CSS doesn't know what 100% means here. So the div element doesn't become 100% of the browser's height.

How to make a div the same height as the window

Making a div the same height as your browser window is relatively straight forward, and it starts with understanding a unit called vh. vh, which stands for viewport height, is a unit representing the current height of your browser window. 100vh is the full height, and any number less than that is a percentage of that height.

Instead of writing height: 100%, we can apply height: 100vh to any element to make it the same size as the browser window.

div {
    height: 100vh
}
Enter fullscreen mode Exit fullscreen mode

It also works for 100vw, which represents the full width of the browser window, vw standing for viewport width.

Top comments (4)

Collapse
 
iamschulz profile image
Daniel Schulz

Working with vh can be tricky on mobile devices. The browser UI pops in and out, changing the usable viewport height, while 100vh stays the same. Depending on how you define 'browser window', svh, lvh and dvh or even a mix of those with clamp() might be a better solution.

The same goes for vw and scrollbars, by the way. A use case for that would be Safari, which displays a solid scrollbar when a mouse is connected, and a self-collapsing one with touchpads.

Collapse
 
smpnjn profile image
Johnny Simpson

you are right, on mobile it's confusing with collapsing navigation items. Kind of dumb it doesn't solve itself automatically.

Collapse
 
margu86 profile image
Margu

It also works for 100vw, which represents the full width of the browser window, vw standing for vertical width

You mean vw stands for viewport width and vh for viewport height.
While Viewport = the browser window size.

Collapse
 
smpnjn profile image
Johnny Simpson • Edited

true my bad typo.