How to Center Vertically Using Flexbox in CSS
To center content vertically using
flexbox, set the container's display to flex and use align-items: center;. This aligns the flex items vertically in the middle of the container.Syntax
Use the following CSS properties on the container element:
display: flex;- turns the container into a flex container.align-items: center;- centers the items vertically along the container's cross axis.
css
.container {
display: flex;
align-items: center;
}Example
This example shows a box with text vertically centered inside a taller container using flexbox.
css
html, body {
height: 100%;
margin: 0;
}
.container {
display: flex;
align-items: center;
justify-content: center; /* centers horizontally too */
height: 200px;
border: 2px solid #333;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
.item {
font-size: 1.5rem;
color: #222;
}Output
<div style="display:flex; align-items:center; justify-content:center; height:200px; border:2px solid #333; background:#f0f0f0; font-family:Arial,sans-serif;"><div style="font-size:1.5rem; color:#222;">Centered Text</div></div>
Common Pitfalls
Common mistakes when centering vertically with flexbox include:
- Not setting
display: flex;on the container. - Using
justify-contentinstead ofalign-itemsfor vertical centering (they control different axes). - Forgetting to set a height on the container, so vertical centering has no space to work.
css
/* Wrong: missing display flex */ .container { align-items: center; height: 200px; border: 1px solid red; } /* Right: add display flex */ .container { display: flex; align-items: center; height: 200px; border: 1px solid green; }
Quick Reference
Summary tips for vertical centering with flexbox:
- Always set
display: flex;on the container. - Use
align-items: center;to center vertically. - Set a fixed or relative height on the container.
- Use
justify-content: center;to center horizontally if needed.
Key Takeaways
Set the container's display to flex to enable flexbox layout.
Use align-items: center to center children vertically inside the container.
Make sure the container has a height for vertical centering to work.
justify-content centers items horizontally, not vertically.
Common errors include missing display:flex or container height.