How to center a DIV element using CSS
How to center a DIV element horizontally and vertically? Name a different approaches.
Let's say that we have the following HTML structure:
<div class="parent">
<div class="child">Centered Content</div>
</div>
Solution 1: Using Flexbox
If the parent container of your div is a flex container, you can center the div both horizontally and vertically with the following CSS:
.parent {
display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */
}
Solution 2: Using Grid
Similar to Flexbox, but with CSS Grid.
place-items
is a shorthand for align-items
and justify-items
.parent {
display: grid;
place-items: center;
}
Solution 3: Using margin: auto
If you want to center a div horizontally, and it has a fixed width, you can use:
.child {
margin: 0 auto; /* auto margin on left and right */
width: 50%; /* or any fixed width */
}
Solution 4: Using position: absolute
If you want to center a div both horizontally and vertically, you can use:
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Summary
- We covered 4 different approaches to center a div using CSS.
- Flexbox is the most versatile approach, and it's the recommended approach.
- Grid is a good alternative to Flexbox, and it's more powerful.
margin: auto
is a good approach if you want to center a div horizontally, and it has a fixed width.position: absolute
is a good approach if you want to center a div both horizontally and vertically.