Explain Codes LogoExplain Codes Logo

How to make a div 100% height of the browser window

html
responsive-design
css
layout
Anton ShumikhinbyAnton Shumikhin·Sep 24, 2024
TLDR

To establish a div to the height of the browser window, implement 100vh in CSS. Here vh equates to 100% viewport height.

.full-height { height: 100vh; /* Make the div a skyscraper */ }

This rule assures the div stretches as tall as the screen itself while being flexible to variable device sizes.

Matters of percentages: Interrelations & Positioning

Where 100vh acts as an often-used crutch, it can be shaken up depending on the heights of the parent containers and the context of positioning. To strengthen the layout with the certainty of a div filling the space as planned, confirm both html and body elements have a height: 100% set:

html, body { height: 100%; /* Laying the "yellow brick road" groundwork for our div kids */ }

Wielding absolute positioning with top: 0; & bottom: 0; manifests a div that willingly stretches vertically to fit the available room. Do ensure parent div elements aren't absoluteor relative positioned as it may haphazardly disrupt the layout, kind of like a pesky traffic jam!

Take note that 1vh equals 1% of the viewport height, acting as a shape-shifter that adjusts responsively. Such adaptability in a multi-column format would require a mix of height: 100vh; and width: 50%; to forge equal-height columns.

Adding pixie dust: Visual distinction

When dabbling with numerous div elements, visual distinction could be the saving grace. Cast spells with background-color to spot the div stretching to its full height visually, within labyrinth-like layouts.

.full-height { height: 100vh; background-color: #e0e0e0; /* Giving this div a new outfit */ }

In the realm of Floating and Flexing

The trickery of float properties could summon solid positioning. However, what if a div is in a Flex or Grid camp? Fret not! In a flex container, the parent can be enchanted with display: flex; while the child div receives the charm of flex: 1;.

This charm makes the child stretch out, voraciously consuming available space in a vertical feast.

Crusading for Responsiveness & Browser compatibility

While the loyal knight 100vh battles consistently in most modern browsers, always fortify the cross-compatibility check! Opera Mini and some mobile browsers might treat vh differently, so be sure to have a strategy for these nemesis browsers.