11/05/2019 21:22 • ☕️ 2 min read
If I could get a pence for each time someone has googled how to centre elements in CSS I would have been a millionaire. So, I guess you saw through my cunning plan - I just need to set a google adds on this page, and I’ll be set for life. 😜
Anyhow lets start:
We have two divs, the parent and child, and we want to centre the child within that parent.
<div class="parent">
<div class="child"></div>
</div>
What are our options then, to make it stick to the center ?
<div>
tags to behave like <table>
and <td>
tags.
So, we can you following .parent {
display: table-cell;
width: 1200px; /* (x)px but cannot be % */
height: 600px;
text-align: center; /*horizontal align*/
vertical-align: middle; /*vertical align*/
}
.child {
width: 250px;
height: 120px;
display: inline-block;
}
This method will work only for the parent with fixed values. Child can have dimensions in percent (%).
.parent {
display: flex;
justify-content: center;
align-items: center;
}
.parent {
display: flex;
}
.child {
align-self: center;
/* justify-self will not work in this case */
}
.parent {
display: flex;
}
.child {
margin: auto;
}
Another useful option if se have need to adjust offset can be:
.child {
margin: calc(50% - 100px) calc(50% - 100px); /* instead of auto */
}
How many pixels need to be deducted depends on the width and height of the child object.
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translate(-50%, -50%);
}
.parent {
display: grid;
justify-content: center; /*horizontal*/
align-content: center; /*vertical*/
}
.parent {
display: grid;
}
.child {
justify-self: center; /*horizontal*/
align-self: center; /*vertical*/
}
That’s it, I wish you happy coding and styling…