Oztaco
Oztaco

Reputation: 3459

Set height to 100% of browser viewport when container is bigger than viewport?

I'm working on a website and I need to set a div's height and width to cover the entire area of the browser viewport like many modern websites. However, I can't simply set its height to 100% because its parent element is another div whose height must be set to bigger than the browser window. Is there another way of doing this?

Here's a code sample set up similar to my website.

HTML

<div class="entireThing">
  <div class="contentBox">
  </div>
  <div class="contentBox">
  </div>
</div>

CSS

.entireThing {
    height: 8000px;
    width: 100%;
}
.contentBox {
    height: 100%; /*This works only if parent is same size as window*/
}

Upvotes: 5

Views: 15820

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240868

5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

Use viewport-percentage lengths. In this case, 100vh.

.contentBox {
    height: 100vh;
}

Updated Example


You can also use calc() to subtract the 10px top/bottom margins:

.contentBox {
    height: calc(100vh - 20px); /* Subtract the 10px top/bottom margins */
    margin: 10px;
    color: white;
    background-color: #222;
}

Updated Example

..it's just worth pointing out that you need to establish a new block formatting context on the parent element in order to prevent the collapsing margins.

Upvotes: 17

Related Questions