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?
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!