Center an Element Horizontally and Vertically using Flexbox

Ali Spittel
InstructorAli Spittel

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

We have a parent HTML element that takes up the height and width of the page. We will make that parent element into a flex container, and then vertically center its child element using align-items: center;. Finally, we'll use justify-content: center; to horizontally center the element.

Ali Spittel: [0:00] I have some pre-written HTML. I have a main tag and then a section with a class content within it. That content has a height and width on it that takes up the full page. I'm going to make it so that my main element also takes up the full height and width of the page.

[0:16] Then I'm going to add display: flex to my main element to make it into a flex container. I'm also going to add justify-content: center to center my content horizontally. I'll do align-items: center, in order to vertically center my child element within its parent.

[0:43] With just a few lines of code, I can horizontally and vertically center an element using flexbox.

[0:49] I created a flex container on main, the parent element of the items that I wanted to center by adding display: flex. Then, I used justify-content: center to center my content along the main flex axis, in this case horizontally. I used align-items: center, to center my child element along the cross axis, which in this case was vertical.