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*/
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With