How to Center a Div Using Flexbox in CSS
To center a
div using Flexbox, set the parent container's display to flex, then use justify-content: center; to center horizontally and align-items: center; to center vertically. This aligns the child div perfectly in the middle of the parent.Syntax
Use the following CSS properties on the parent container:
display: flex;activates Flexbox layout.justify-content: center;centers child elements horizontally.align-items: center;centers child elements vertically.
css
.parent {
display: flex;
justify-content: center;
align-items: center;
}Example
This example shows a parent container with a child div centered both horizontally and vertically using Flexbox.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Center Div with Flexbox</title> <style> body, html { height: 100%; margin: 0; } .parent { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; } .child { width: 150px; height: 150px; background-color: #4a90e2; color: white; display: flex; justify-content: center; align-items: center; font-size: 1.2rem; border-radius: 8px; } </style> </head> <body> <div class="parent"> <div class="child">Centered Box</div> </div> </body> </html>
Output
A full browser window with a light gray background and a blue square box in the center containing white text 'Centered Box'. The box is perfectly centered horizontally and vertically.
Common Pitfalls
Common mistakes when centering with Flexbox include:
- Not setting
display: flex;on the parent container. - Forgetting to set height on the parent, so vertical centering has no effect.
- Using
align-contentinstead ofalign-itemsfor vertical centering. - Trying to center the child with margin auto without Flexbox.
css
/* Wrong: Missing display flex */ .parent { justify-content: center; align-items: center; height: 100vh; } /* Right: Include display flex */ .parent { display: flex; justify-content: center; align-items: center; height: 100vh; }
Quick Reference
Remember these key points for centering with Flexbox:
- display: flex; activates Flexbox.
- justify-content: center; centers horizontally.
- align-items: center; centers vertically.
- Parent needs a height for vertical centering.
Key Takeaways
Set the parent container's display to flex to enable Flexbox layout.
Use justify-content: center to center horizontally and align-items: center to center vertically.
Ensure the parent has a height for vertical centering to work.
Common errors include missing display:flex or forgetting parent height.
Flexbox centering works for any child element inside the flex container.