Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

layout

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*/
}
like image 579
Oztaco Avatar asked Jan 17 '15 22:01

Oztaco


1 Answers

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.

like image 138
Josh Crozier Avatar answered Sep 27 '22 22:09

Josh Crozier