No fancy things here, just click a method below and go.
The most googled search that we always forget. How to center a div?!
No fancy things here, just click a method below and go.
Note: Simple, reliable, and still a go-to.. this or the grid method below will center anything in modern browsers, so pick whichever you already use.
Your HTML:
<div class="modern-flex">
<p>Centered with Flexbox!</p>
</div>
Your CSS:
.modern-flex {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 2px dashed #5f66c7;
}
Centered with Flexbox!
Note: The shortest answer in the book. Two properties, centered both ways, works everywhere.
Your HTML:
<div class="grid-center">
<p>Centered with Grid!</p>
</div>
Your CSS:
.grid-center {
display: grid;
place-items: center;
height: 200px;
border: 2px dashed #ed7966;
}
Centered with Grid!
Note: The new kid (2024). One line centers vertically on a plain block element.. no flex, no grid. Add text-align for horizontal and you're done. Needs an up-to-date browser. Everything below this point is the old-school stuff.. it all still works, we just don't reach for it much anymore.
Your HTML:
<div class="block-center">
<p>Centered with align-content!</p>
</div>
Your CSS:
.block-center {
align-content: center;
text-align: center;
height: 200px;
border: 2px dashed #444bbd;
}
Centered with align-content!
Your HTML:
<div class="horizontally">
<p>A lovely horizontally positioned div just for you.</p>
</div>
Your CSS:
.horizontally {
margin: auto;
border: 2px solid #4a3b36;
width: 50%;
}
A lovely horizontally positioned div just for you.
Your HTML:
<div class="vertically">
<p>A pretty vertically positioned div just for you.</p>
</div>
Your CSS:
.vertically {
display: inline-block;
position: relative;
top: 50%;
transform: translate(0, -50%);
border: 2px solid #4a3b36;
}
A pretty vertically positioned div just for you.
Your HTML:
<div class="hVParent">
<div class="horizontally-vertically">
<p>A beautiful horizontally AND vertically positioned div just for you.</p>
</div>
</div>
Your CSS:
.hVParent {
position: relative;
}
.horizontally-vertically {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 2px solid #4a3b36;
}
A beautiful horizontally AND vertically positioned div just for you.
Your HTML:
<div class="parent-div">
<div class="child-div"><p>Inception div - queue inception music.</p></div>
</div>
Your CSS:
.parent-div{
background: #8a6f66;
justify-content: center;
display: flex;
height: 250px;
width: 250px;
}
.child-div{
background: #fae5df;
align-self: center;
padding: 1rem;
}
Inception div - queue inception music.
Source: Multiple Stackoverflow threads..
Questions? Concerns? See something to fix? Email
me :)