Center an Element Horizontally and Vertically using Flexbox

Ali Spittel
InstructorAli Spittel
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years 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.

~ 3 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today