4-ways-to-center-div-thumbnail
CSS HTML

4 Ways to Center Div with CSS

“Human went to the moon 50 years ago but we’re still struggling to center div with CSS” – Unknown
Well isn’t that true? But fear not, in this post, I’m going to show you 4 ways on how to center div with CSS including pros and cons for each one. Let’s check it out!

1. Flex Layout

The first and most simple method is to use a flex layout. Simply add display:flex and justify-content center for horizontal justification and align-item center for vertical alignment to parent div.

display: flex;
justify-content: center;
align-items: center;

The advantage of flex display is you don’t need to specify the width and height of the div at all (ex. div with just text) Also it can be used on both inline and block element. Flex layout is quickest way to to center multiple elements in a single div.

4-ways-center-div-css

2. margin: 0 auto

margin: 0 auto;

This is a quick solution and quite popular. Just adding it to any div and it’s done. However, there are lots of limitation of this approach. First, we can only use this for element that have width defined. The element must have block or table display and must not have fixed or absolute positioned. And, obviously, you can’t use it for vertical align. So it’s not quite flexible and should be used for a certain scenario.

3. text-align and inline-block

The third method is to use a combination of text-align and inline-block display. Simply add text-align center to parent div and set the child div display to inline-block.

.example-div {
    display: inline-block;
}
.parent-div {
    text-align: center;
}

This will force our div to behave like inline element and therefore subjected text-align center. The difference between this method and margin: 0 auto is we don’t need the width to be specified. Then again, you can use it for vertical align.

4. 2D Transform

The final approach is using 2D transform. First we need to set the element position to absolute and top/left to 50%. This will the div to the center of the screen. Then add minus 50% translate for both x and y to offset the element size.

.example-div {
    top: 50%;
    left: 50%;
    transform: translate(-50% , -50%);
    position: absolute;
}

Our div will always be at the center of the screen and will ignore all other elements. (due to absolute position) Very useful if you want to use your div to overlay others but still you will need to define width and height for the div to make this works

Note: you can change the position to relative if you want to center the div relative to the parent instead of the screen.

Love this tutorial? Feel free to like or subscribe to our Facebook and Youtube Channel to stay connected. Thanks for keep reading til the end 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *