How to Center a Div with CSS

hyperion

View Profile
80 views
Jun 26, 2025

Here's how to center a <div> using Flexbox:

.parent {
 display: flex;
 justify-content: center;
 align-items: center;
 height: 300px; /* Example height for vertical centering */
}
.child {
 /* Styles for the div you want to center */
}

Alternatively, you can use CSS positioning:

.parent {
 background: gray;
 height: 300px;
 width: 300px;
 position: relative;
}
.child {
 background-color: orange;
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%,-50%);
}

You can also use CSS Grid