3 Different Ways to Center a Div with CSS
I know, there are more ways to center a div with CSS, but in this post I want to focus on the most useful ones, in my opinion.
Center a Div horizontally with Auto-Margins
I think this is the first way of centering a Div I learned in my life, many years ago. But it’s still useful to me sometimes, event today.
By settinging the margin to auto, we can center a div horizontally.
div {
margin: 0 auto;
}
Have a look at the result:
Center a Div using Flexbox
I just love CSS flexbox. It’s just so easy to use and powerful. Of course flexbox can be used to center a Div horizontally and even vertically. Let me show you:
.parent {
display: flex;
justify-content: center;
align-items: center;
}
First we set the display property of the parent container to flex, to enable the flex layout.
justify-content
centers the div horizontallyalign-items
centers the div vertically
Center a Div with Absolute Positioning
Ok, finally the last way to center a div, I will show you in this post. Absolute positioning, combined with a clever transform, lets us center Divs horizontally and vertically.
Have a look:
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
If you want more tips like that, please let me know! 😊