Centering elements with Flexbox

 
new course
CSS grid landing page tutorial (36min)

Lesson info

Lesson info

Centering elements vertically used to be a challenge in web design, until flexbox arrived on the scene. With flexbox it’s easy to center any element(s) vertically in its parent element. In this video, we'll show you how to use flexbox to center one or more elements. In these examples, the parent element has been set to a height of 100vh, which is 100% of the viewport height, so the items are centered relative to the viewport, as well as to their parent containers.

Clone this projectDownload project assetsDownload lesson assets

Transcript

Until recently, vertically centering a child element inside a parent element required absolute positioning, transforming along the y-axis, and a graduate degree in materials engineering. With Flexbox, centering is straightforward and highly effective.

We'll do this with a single element, then we'll do it again with multiple elements, then we'll do it yet again with a single element containing multiple elements.

Let's do it with a single element. Super simple. Now in all these examples, we’re using Sections with set heights, so that we can demonstrate vertically centering flex items. Let’s go to our asset manager, and drag in an image. All we have to do is select the section, set it to flex, and justify and align to center. That’s literally it; there’s nothing else.

Let's talk multiple elements. Here are some div blocks in a section. We use our flex layout options to control whether we're horizontally or vertically displaying our flex items. And to center them, we just click to center them.

That's multiple elements.

Let's do a single element containing multiple elements. This is common with sections and containers. Say we want to center our container (which contains a ton of content) inside our section. Okay. Select the section, we're setting it to flex. And we justify and align to center. That's it.

So, three examples, that's centering using Flexbox.