How to Center a Div in CSS
CSS • Web Development • 5 min read
Five different methods to center elements in CSS, from flexbox to grid, with examples you can copy and paste.
How to Center a Div in CSS
Centering elements is one of the most common tasks in CSS, and it’s surprisingly tricky for beginners. There are several ways to center a div, each with its own use cases. Let’s walk through the most reliable methods.
1. Flexbox Method
Flexbox is the most modern and flexible way to center elements. It works on both axes (horizontal and vertical) with just a few lines of CSS.
.parent {
display: flex;
justify-content: center; /* horizontal center */
align-items: center; /* vertical center */
height: 300px;
}
.child {
width: 200px;
height: 100px;
background: lightblue;
}
2. CSS Grid Method
CSS Grid offers an even shorter syntax with the place-items property. This method is great when you want a simple centering solution.
.parent {
display: grid;
place-items: center;
height: 300px;
}
.child {
width: 200px;
height: 100px;
background: lightgreen;
}
3. Margin Auto Technique
This classic method works for horizontal centering of block-level elements. You need to set a width on the element for margin auto to work.
.child {
width: 200px;
margin: 0 auto; /* centers horizontally */
background: lightyellow;
}
4. Position + Transform Technique
This method is useful when you need absolute positioning. It combines absolute positioning with the transform property to center an element.
.parent {
position: relative;
height: 300px;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 100px;
background: lightcoral;
}
5. Text-Align for Inline Elements
If you’re centering inline or inline-block elements, you can use text-align on the parent container.
.parent {
text-align: center;
height: 300px;
line-height: 300px; /* vertical centering */
}
.child {
display: inline-block;
width: 200px;
height: 100px;
background: lightpink;
}
Note:
For most modern web development, the Flexbox method is recommended as your go-to solution for centering. It's supported in all modern browsers and handles both horizontal and vertical centering elegantly. Use CSS Grid when you need more complex layouts, and reserve the other methods for specific edge cases.Which Method Should You Use?
For simple centering tasks, Flexbox is your best choice. It’s readable, maintainable, and works in all modern browsers. If you’re working with older browser versions, margin auto might be a safer option for horizontal centering.
Remember that centering is just one aspect of layout. As you learn more CSS, you’ll discover that these techniques work together to create sophisticated, responsive designs.