codelord.net

Code, Angular, iOS and more by Aviv Ben-Yosef

CSS Tip: Elements with Height 100% - Fixed Amount

| Comments

A quick tip that I just find myself smiling whenever I use it successfully and feel dumb for not using it earlier:

Nowadays, it is very often that we want to layout an element to fill all of its parent’s height (or width) except for a fixed amount. For example, a view with a top header and body that should fill the rest.

Up until recently I used to solve this by using flexbox, where browser support allowed me.

But a few weeks ago a friend showed me this really really really really neat trick. I’ve known about CSS’s calc() for a while, but I didn’t know it could be used for this, and didn’t know it had such a wide support base:

1
2
3
4
5
<div class="container">
    <header>My awesome header</header>

    <article>My even more awesome content</article>
</div>
1
2
3
4
5
6
7
8
9
10
11
.container {
    height: 100vh;
}

.container header {
    height: 50px;
}

.container article {
    height: calc(100% - 50px);
}

You can see a simple example here.

Yup. That’s it! Calc away!

Write maintainable Angular, learn the best practices and get prepared for 2.0!

Comments