Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to stretch elements to fit the whole height of the browser window with CSS?
To stretch elements to fit the whole height of the browser window, use the height property and set it to 100%. This technique requires setting the height on both the HTML document and the container element.
Syntax
html, body {
height: 100%;
margin: 0;
}
.container {
height: 100%;
}
Method 1: Using Percentage Height
The most common approach is to set the HTML document and body to 100% height, then apply the same to your container element −
<!DOCTYPE html>
<html>
<head>
<style>
html, body {
height: 100%;
margin: 0;
}
.fullHeight {
height: 100%;
background: linear-gradient(45deg, #667eea, #764ba2);
color: white;
font-family: Arial, sans-serif;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
}
</style>
</head>
<body>
<div class="fullHeight">This div stretches to full browser height</div>
</body>
</html>
A purple gradient div that fills the entire browser window height and width, with centered white text "This div stretches to full browser height".
Method 2: Using Viewport Height (vh)
Modern CSS offers viewport units where 100vh represents 100% of the viewport height −
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
}
.fullHeight {
height: 100vh;
background: #2c3e50;
color: white;
font-family: Arial, sans-serif;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
}
</style>
</head>
<body>
<div class="fullHeight">Full height using viewport units</div>
</body>
</html>
A dark blue div that fills the entire browser window height, with centered white text "Full height using viewport units".
Key Points
- Always remove default margins with
margin: 0on html and body - The percentage method requires height to be set on parent elements
- Viewport units (vh) are more direct and don't require parent height settings
- Use
box-sizing: border-boxto include padding in height calculations
Conclusion
Both percentage height and viewport units effectively stretch elements to full browser height. Viewport units offer a simpler approach, while percentage height provides better legacy browser support.
Advertisements
