How to Center Content Using Flexbox in CSS
To center content using
flexbox, set the container's display to flex, then use justify-content: center; to center horizontally and align-items: center; to center vertically. This method works for both single and multiple items inside the container.Syntax
Use the following CSS properties on the container element:
display: flex;activates flexbox layout.justify-content: center;centers items horizontally.align-items: center;centers items vertically.
css
.container {
display: flex;
justify-content: center;
align-items: center;
}Example
This example shows a box centered both horizontally and vertically inside a container using flexbox.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flexbox Centering Example</title> <style> body, html { height: 100%; margin: 0; } .container { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; } .box { 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="container"> <div class="box">Centered Box</div> </div> </body> </html>
Output
A blue square box with white text "Centered Box" perfectly centered vertically and horizontally on a light gray full screen background.
Common Pitfalls
Common mistakes when centering with flexbox include:
- Not setting
display: flex;on the container, so flex properties don’t work. - Forgetting to set a height on the container, so vertical centering has no effect.
- Using
align-contentinstead ofalign-itemsfor vertical centering of single-line flex containers.
css
/* Wrong: missing display flex */ .container { justify-content: center; align-items: center; height: 100vh; background-color: #eee; } /* Right: add display flex */ .container { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #eee; }
Quick Reference
| Property | Purpose | Example Value |
|---|---|---|
| display | Enables flexbox layout | flex |
| justify-content | Centers items horizontally | center |
| align-items | Centers items vertically | center |
| height | Needed for vertical centering | 100vh or fixed height |
Key Takeaways
Set the container's display to flex to enable flexbox.
Use justify-content: center to center horizontally.
Use align-items: center to center vertically.
Ensure the container has a height for vertical centering to work.
Common mistakes include missing display:flex or container height.