How to Center with justify-content in CSS: Simple Guide
Use
justify-content: center; on a flex container to center its child elements horizontally. This works only if the container has display: flex; or display: inline-flex;. It aligns items along the main axis, which is horizontal by default.Syntax
The justify-content property aligns flex items horizontally inside a flex container. It controls the distribution of space along the main axis.
justify-content: center;centers items horizontally.display: flex;ordisplay: inline-flex;must be set on the container.
css
.container {
display: flex;
justify-content: center;
}Example
This example shows a box centered horizontally inside a container using justify-content: center;. The container uses flex layout, so the child box moves to the center along the horizontal axis.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Center with justify-content</title> <style> .container { display: flex; justify-content: center; border: 2px solid #333; height: 100px; align-items: center; /* vertically center for better look */ } .box { width: 100px; height: 50px; background-color: #4CAF50; color: white; display: flex; justify-content: center; align-items: center; font-weight: bold; } </style> </head> <body> <div class="container"> <div class="box">Centered</div> </div> </body> </html>
Output
A green rectangular box with white text 'Centered' horizontally centered inside a gray-bordered horizontal container.
Common Pitfalls
Common mistakes when using justify-content: center; include:
- Not setting
display: flex;on the container, sojustify-contenthas no effect. - Trying to center block elements without flexbox, which won't work with
justify-content. - Confusing
justify-content(horizontal alignment) withalign-items(vertical alignment in default flex direction).
css
/* Wrong: no flex container */ .container { justify-content: center; border: 1px solid black; height: 100px; } /* Right: add flex display */ .container { display: flex; justify-content: center; border: 1px solid black; height: 100px; }
Quick Reference
justify-content values for horizontal alignment in flexbox:
| Value | Effect |
|---|---|
| flex-start | Align items to the left (start) |
| center | Center items horizontally |
| flex-end | Align items to the right (end) |
| space-between | Distribute items with space between them |
| space-around | Distribute items with space around them |
| space-evenly | Distribute items with equal space around |
Key Takeaways
Set
display: flex; on the container before using justify-content.justify-content: center; centers flex items horizontally along the main axis.Use
align-items to control vertical alignment in a flex container.Without flex display,
justify-content does not work.Common values like
flex-start, center, and flex-end control horizontal item placement.