Vertical alignment and 100% height with Flexbox & CSS3

Before flexbox, in old days of yore (i.e. 2007), getting something to vertically align within an element or have a particular element span the remaining percent of a layout was quite the task. It involved various hacks that may or may not have worked with specific versions of specific browsers of that time period. Using flexbox and CSS3, this can be achieved in just about 2 lines of CSS.

These days, there is a glorious savior: Flexbox!

Flexbox is mostly a fancy name for using the CSS display: flex. Once you slap this on one of your elements, a container div for example, the CSS3 gloves are off!

Let’s solve our vertical alignment issue first. In this sample, we will have a left menu that has a top, middle and bottom. We want the middle to take up the space of what the top and bottom do not.

.flex-container {
 display: flex;
 flex-direction: column;
 width: 100%;
 height: 100%;
}

.flex-grow {
 flex-grow: 1;
}

<div class="flex-container">
  <div class="flex-col">top</div>
  <div class="flex-col flex-grow">middle</div>
  <div class="flex-col">bottom</div>
</div>

The majority of the work is actually done by the flexbox container. Using flexbox allows the element to use the CSS flex-direction: column. By assigning the middle child div element to the have the CSS flex-grow: 1, it will automatically take up the remaining space!

Next, we conquer vertical alignment within elements. Using the same HTML from above, we can apply similar CSS. This time we are going for a flex-direction: row look.

.flex-container {
 display: flex;
 flex-direction: row;
 width: 100%;
 height: 25%;
}

.flex-grow {
 flex-grow: 1;
}

.flex-col {
  display: flex;
  align-items: center;
  justify-content: center;
}

<div class="flex-container">
  <div class="flex-col flex-grow">left</div>
  <div class="flex-col">middle</div>
  <div class="flex-col">right</div>
</div>

With this example, we assign display: flex to both the container and the child elements. Then we add the 1-2 punch of align-items: center and justify-content: center to align our hypothetical nav items both vertically and horizontally.

You’ll also notice that we snuck in some flex-grow goodness in there to not worry about the width of our middle and right items.

Leave a Reply

Your email address will not be published. Required fields are marked *