Matteo Bianchi
Posted on July 10, 2024
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>
π πͺ π
π©
Matteo Bianchi
Posted on July 10, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.