How to Use justify-content in CSS for Layout Alignment
justify-content property in CSS aligns items horizontally inside a flex or grid container. You set it on the container to control how extra space is distributed between and around items along the main axis.Syntax
The justify-content property is used inside a flex or grid container to align child items horizontally. It accepts several keyword values that control the distribution of space.
flex-start: Items align to the left (start).flex-end: Items align to the right (end).center: Items align in the center.space-between: Items spread out with equal space between.space-around: Items have equal space around them.space-evenly: Items have equal space between and around.
.container {
display: flex; /* or grid */
justify-content: center; /* example value */
}Example
This example shows a flex container with three boxes aligned using justify-content: space-between. The boxes spread out horizontally with equal space between them.
html, body {
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background: #f0f0f0;
}
.container {
display: flex;
justify-content: space-between;
width: 60%;
background: white;
padding: 1rem;
border: 2px solid #ccc;
}
.box {
width: 80px;
height: 80px;
background: #4a90e2;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
border-radius: 8px;
}Common Pitfalls
One common mistake is using justify-content on elements that are not flex or grid containers. It only works when display is set to flex or grid. Another pitfall is confusing justify-content with align-items, which controls vertical alignment in flexbox by default.
Also, remember that justify-content aligns items along the main axis, which is horizontal by default in flexbox but vertical if you change flex-direction.
/* Wrong: justify-content on a block container */ .container { justify-content: center; /* No effect without flex or grid */ } /* Right: add display flex */ .container { display: flex; justify-content: center; }
Quick Reference
Here is a quick summary of justify-content values and their effects:
| Value | Effect |
|---|---|
| flex-start | Items align to the start (left) |
| flex-end | Items align to the end (right) |
| center | Items align in the center |
| space-between | Items spread with equal space between |
| space-around | Items have equal space around them |
| space-evenly | Items have equal space between and around |
Key Takeaways
justify-content on flex or grid containers to align items horizontally.justify-content works along the main axis, which can change with flex-direction.display: flex or display: grid on the container.space-between and space-around help create balanced spacing.