โ† Home

Center an Element Horizontally and Vertically with Flexbox

Did you know that you can center an HTML element horizontally and vertically in just a few lines of code using CSS Flexbox?

View on Egghead

First, we need a parent HTML element with some child elements inside it. For example, this main element with a section inside of it.

<main>
  <section class="content">
    <h1>Hi! ๐Ÿ‘‹</h1>
    <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolor
      perferendis mollitia saepe harum praesentium libero unde reprehenderit
      dolorum inventore veritatis dolorem nostrum, tempora sapiente optio,
      sed maxime consectetur assumenda est.
    </p>
  </section>
</main>

We need to make sure the main element takes up the height of the page, as well as its parent elements:

html,
body,
main {
  height: 100%;
  width: 100%;
}

Then, we need to make the main element into a flex container by adding display: flex;. The flex container should be the immediate parent element to the element we want to center.

Then, we'll add justify-content: center; to center the content along the main flex axis, which in this case is horizontally. We'll also use align-items: center; to center the child element along the cross axis, which in this case is vertical.

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

๐ŸŽ‰ Now our content is centered!

Be the first to know about my posts!

Share this post with a friend!

LinkedIn
Reddit