How to Center a Div in CSS
Centering a div
is the most impossible thing
1. Centering with Flexbox
Flexbox is a modern way to center content both vertically and horizontally:
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
<div class="container">
<div class="centered-div">Centered Content</div>
</div>
2. Centering with Grid
CSS Grid can also center content:
.container {
display: grid;
place-items: center;
height: 100vh;
}
<div class="container">
<div class="centered-div">Centered Content</div>
</div>
3. Centering with Absolute Positioning
You can center a div using absolute positioning:
.container {
position: relative;
height: 100vh;
}
.centered-div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="container">
<div class="centered-div">Centered Content</div>
</div>
4. Centering with Margin Auto
For simple horizontal centering, use margin: auto:
.centered-div {
width: 50%;
margin: 0 auto;
}
<div class="centered-div">Centered Content</div>
5. Centering with inline-block display
For inline or inline-block elements:
.container {
text-align: center;
line-height: 100vh;
}
.centered-div {
display: inline-block;
vertical-align: middle;
line-height: normal;
}
<div class="container">
<div class="centered-div">Centered Content</div>
</div>
Top comments (17)
You missed centring using Markdown 🤣💗
How do you did? 😂
I am sorry for my english. I am from Angola
Paragraphs with nbsp in them and the center element! 💗
You don’t center a div. Life’s too short to center a div.
For those who would like to practice some concepts like Flexbox, I suggest the Flexbox Froggy game, for Grid I suggest Grid Garden game, and if you just wanna some free quick challenge I highly recommend CSSBattle. Remember, practice is the key!
awesome sharing, thank you!
I love grid! It only came 30 years too late, in the meantime my hair has become significantly less (due to plucking out of sheer desperation).
FBI open up, he centered a Div 😂😂
😂
Some are missing 👀
Saw that too heheh👀
Ingles: Thank you very much for your comment! I was not aware of those 3 resources that you provided us, thank you very much again.
Spanish: Muchas gracias por su comentario! no tenia conocimiento sobre esos 3 recursos que nos proporciono, muchas gracias nuevamente.
Great article. I typically use Flexbox and/or "margin: 0 auto;" for centering a div element. There are of course other ways of accomplishing the same task, which you outline in this post.
You don't need to remember how to do it. Your job as a software engineer is to decide why - and whether - it is necessary.
Ask to @ezsnippet for more ways😁.
Kind of issues that keeps BE devs away from UI 😂
Great! Good job Matteo