Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 986 of the free egghead.io lessons, plus get CSS content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Create a fixed-fluid-fixed layout using CSS calc()

0:59 CSS lesson by

CSS calc() allows you to mix and match units to get real-time calculations. It's useful when you need to size elements but you have some unknown number that you have to account for.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

CSS calc() allows you to mix and match units to get real-time calculations. It's useful when you need to size elements but you have some unknown number that you have to account for.

Avatar
Wayne

Where is the code?

Avatar
Damon Bauer

Hmm.. not sure what's up with the code tab, but here's a link:

http://plnkr.co/edit/CDbdPh?p=preview

In reply to Wayne
Avatar
devilboy

Thanks Damon

Have a nice weekend

In reply to Damon Bauer
Avatar
James

There are issues with the sound quality on your lessons. The volume goes up and down from lesson to lesson. I have my PC volume on max and this lesson (Create a fixed-fluid-fixed layout using CSS calc()) I can barely hear.

Let's start out by targeting the main element. We'll set its margin-left property to 5rem. This 5rem equals the width of the element. Now for the width, let's take width and we'll set that to a calc() function of 100% - 25rem. Here the 25rem comes from the 5rem width of the element plus the 20rem width of the aside element.

style.css

nav {
    position: fixed;
    top: 0; left: 0;
    width: 5rem;
    height: 100%;
}

aside {
    position: fixed;
    top: 0; right: 0;
    height: 100%;
    width: 20rem;
}

main {
    margin-left: 5rem;
    width: calc(100% - 25rem);
}

Now when I resize my window, the main element is still positioned in the correct location, and it grows and shrinks depending on the remaining available space.

Window Resize

We can take this one step further by repeating this pattern inside of a @media query to ensure that the layout functions properly even when the elements change size.

style.css

@media screen and (max-width: 40em) {
    nav {
        width: 3rem;
    }

    main {
        margin-left: 3rem;
        width: calc(100% - 15rem);
    }

    aside {
        width: 12rem;
    }
}

If I resize my window, the nav and the side elements shrink, and the main element continues to take up the remaining space thanks to the calc() function.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?