Skip to main content

How to center a DIV element

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>

Approach 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 */
}

Approach 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;
}

Approach 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 */
}

Approach 4: Using Absolute Positioning

.parent {
position: relative;
}

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