How to Center a Div in CSS (All Methods)

1. Center using Flexbox (Best & Most Used)

Centers a div horizontally and vertically using Flexbox.

BOX
.parent{
    display: flex;
    justify-content: center;
    align-items: center;
}
✅ Recommended method for modern websites

2. Center using CSS Grid

Grid allows perfect centering using one line.

BOX
.parent{
    display: grid;
    place-items: center;
}
✅ Clean & powerful (modern CSS)

3. Center using margin: auto (Horizontal only)

Used when you only want horizontal centering.

BOX
.box{
    margin: auto;
}
⚠ Works only if width is fixed

4. Center using Position + Transform

Classic method using position and transform.

BOX
.box{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
⚠ Still used in modals & popups

5. Center using Position Absolute (Old Method)

Uses top, bottom, left, right with margin auto.

BOX
.box{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

6. Center Text inside a Div

Used for text or inline elements.

TEXT
.parent{
    text-align: center;
    line-height: 200px;
}
⚠ Not suitable for complex layouts