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

To make a <div> take up 100% of the browser window height, use one of these CSS methods:

1. Using Viewport Units (Modern & Recommended)

Set the height to 100vh (100% of the viewport height):

div {
  height: 100vh;
}

Advantages:

  • Works regardless of parent elements.
  • No need to set heights on parent containers like <html> or <body>.

2. Traditional Percentage Height

Set the <html> and <body> heights to 100%, then target the <div>:

html, body {
  height: 100%;
  margin: 0; /* Remove default margins */
}

div {
  height: 100%;
}

3. Flexbox Method (For Full-Page Layouts)

Make the <body> a flex container:

body {
  margin: 0;
  min-height: 100vh;
  display: flex;
}

div {
  flex: 1; /* Fills remaining space */
}

Key Notes

  • Reset Default Margins: Browsers add margins to <body>, so set margin: 0.
  • Viewport Units (vh):
  • 100vh = 100% of the viewport height.
  • Avoid height: 100% unless parent heights are explicitly set.
  • Content Overflow: Use min-height: 100vh if the content might exceed the viewport.

Full Example

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      margin: 0; /* Remove default margins */
    }

    .full-height {
      height: 100vh;
      background: lightblue;
    }
  </style>
</head>
<body>
  <div class="full-height"></div>
</body>
</html>

Common Issues & Fixes

IssueSolution
Scrollbars appearAdd overflow: hidden to <body> (use cautiously).
Parent containers not full heightUse 100vh instead of 100%.
Mobile browser quirksAdd height: -webkit-fill-available for Safari.

Use 100vh for simplicity or Flexbox for complex layouts!

Leave a Reply

Your email address will not be published. Required fields are marked *