Create a Website Layout with Flexbox

Here we'll use flexbox to create a three column layout — the one that's often referred to as "the holy grail" layout.

Flexbox is ideal for creating commonly used website layouts such as the three-column, so-called holy grail layout, where all columns need to remain at full height, regardless of how much (or little) content resides within them. And where the main content comes before the navbar in the source code, but not in the presentation.

Prior to flexbox, this layout was notoriously difficult to achieve without using a hack of some sort. Developers would often have to do things like add extra markup, provide negative margins, and use other tricks in order to get everything to line up correctly regardless of the amount of content or the screen size.

But as the above example shows, flexbox makes it quite trivial. Here's a quick rundown of the code.

In the example, we make the #main element the flex container, and leave the header and footer as block elements. In other words, only the middle bit is flexbox.

Here's the bit that makes it a flex container:

We simply use display: flex to make it a flex container.

Notice that we also set the min-height to a value using the calc() function. What we're doing here is setting the main area to 100 percent of the viewport's height, minus the height of the header and footer (20vh each). This will ensure that the layout takes up the full height of the screen, even when there's not much content. This means that the footer will never rise up and leave blank space underneath if the content doesn't take up the full screen height.

The above min-height calculation was reasonably straightforward, given that we applied box-sizing: border-box to all elements. If we hadn't done that, we'd also need to include padding in the amount to subtract.

So after setting the flex container, we then deal with the flex items.

In the first instance we only provide one value, so it sets the flex-grow property.

In the second instance we provide all three values. We explicitly set the nav and aside to have a zero grow factor, a zero shrink factor, and a 20vw flex basis. Flex basis is the initial main size of the flex item, before free space is distributed. So we're basically just setting the width of the nav and aside, as well as setting its color.

That's all the flexbox code we needed to get this layout working.

So this example only uses flexbox for the middle section — the main content area. If you wanted to use flexbox for the whole page, you could do that too. In this case we could achieve that using nested flex containers.