DEV Community

Cover image for 5 Easy Ways to Center a div Element in CSS
Patricia Cosma
Patricia Cosma

Posted on • Updated on

5 Easy Ways to Center a div Element in CSS

The nicest thing about CSS is that one problem can be solved in many ways. It doesn’t matter that you don’t know all the possibilities - you won’t struggle to find your way out of the problem.

However, you can be prepared by already knowing that it is possible to solve what you have at hand in many ways, as long as you are creative. Today we will walk through a simple and common situation you will encounter in your project: how to center your div element.

option I

This will horizontally align the block to the center of the parent. You can also add width to your .child to prevent it from stretching out to the edges of the .parent.

.parent {
    display: flex;
}
.child {
    margin: auto;
}
Enter fullscreen mode Exit fullscreen mode

option II

Probably one of the first solutions you’ll learn when aligning items because of its simplicity. align-items will pack the items vertically to the center, while justify-content will take care of the horizontal part.

.parent {
    display: flex;
    align-items: center;
    justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

option III

Setting the top and the bottom may look pretty straightforward. However, if you stop there, the browser will just center the element’s edges and it will display it off-center. Adding the transform property will solve that issue.

.parent {
    position: relative;
}

.child {
    position: absolute;
    top: 50%;
    bottom: 50%;
    transform: translate (-50%, -50%);
Enter fullscreen mode Exit fullscreen mode

option IV

You may look to find a way to write as little code as possible in your project when that’s possible. Using the place-items shorthand property, which will align your item both vertically and horizontally, you’re basically getting rid of setting the block and inline directions (align-items & justify-content)

.parent {
    display: grid;
    place-items: center;
}
Enter fullscreen mode Exit fullscreen mode

option V

Last in line for today is another shorthand property called inset, which can help you center your div element. margin: auto will behave as in the first example, while inset corresponds to top, bottom, left and right.

.parent {
    position: relative;
}

.child {
    position: absolute;
    inset: 0;
    margin: auto;
}
Enter fullscreen mode Exit fullscreen mode

Although they are far from being the only options when centering the div elements in your CSS, I hope you’ll make use of them throughout your exploration.

Can you think about another way you can center your div next time? 🤓


Cover photo by Alejandro Barba on Unsplash

Top comments (0)