Sometimes, we want to center an element horizontally and vertically with CSS.
In this article, we’ll look at how to center an element horizontally and vertically with CSS.
How to center an element horizontally and vertically with CSS?
To center an element horizontally and vertically with CSS, we use flexbox.
For instance, we write
<div class="container">
<span>I'm vertically/horizontally centered!</span>
</div>
to add some elements.
Then we write
html,
body,
.container {
height: 100%;
}
.container {
display: flex;
align-items: center;
justify-content: center;
}
to make the div a flex container with display: flex;
.
Then we write align-items: center;
and justify-content: center;
to vertically and horizontally center the contents in the container respectively.
Conclusion
To center an element horizontally and vertically with CSS, we use flexbox.