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 (20)
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! 💗
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!
You don’t center a div. Life’s too short to center a div.
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👀
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.
I've recently been using ChatGPT to do simple tasks like this. It's quicker & I can focus on the more important parts of the code.
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.
I recently used #3 - Centering with Absolute Positioning. One thing to note is that the top, left, right, bottom properties are relative to its parent & translate is relative to the element's own size.