How to center a <div> in CSS ?

Let's discover together tree ways to center a div in HTML/CSS !
Thursday, December 23, 2021

Hi ! Here I will show you three ways to center a div in HTML and CSS !

This text is horizontally and vertically centered 😌

Use the “absolute position” trick

Note: this technique works on (very) old browers like Internet Explorer:

<style>
p {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
</style>
<article>
<p>Center</p>
</article>

Use the “flexbox” trick

On modern browsers, you can use Flexbox like this:

<style>
article {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
</style>
<article>
<p>Center</p>
</article>

Use the “grid” trick

On modern browsers, you can use Grid like this too:

<style>
article {
display: grid;
place-items: center;
height: 100vh;
}
</style>
<article>
<p>Center</p>
</article>

🎉: Tada !


Recommended articles