CSS
How to Vertically and Horizontally Align Flexbox to Center
Flexbox is one of the most powerful layout tools in modern CSS, making it easier than ever to center content both vertically and horizontally. Whether you’re working with text, buttons, cards, or entire sections, Flexbox gives you full control over alignment with just a few lines of code.
In this blog post, you’ll learn how to align items to the exact center of a container using Flexbox, along with practical examples and best practices.
✅ The Goal
You want to align content like this:
+--------------------------+
| |
| [Centered] |
| |
+--------------------------+
This means centering the item both vertically and horizontally within its parent container.
🧪 Basic Example: Flexbox Centering
📄 HTML
<div class="container">
<div class="content">Centered Item</div>
</div>
🎨 CSS
.container {
display: flex;
justify-content: center; /* Horizontal alignment */
align-items: center; /* Vertical alignment */
height: 100vh; /* Full viewport height */
background-color: #f0f0f0;
}
.content {
padding: 20px;
background-color: #4f46e5;
color: white;
font-weight: bold;
border-radius: 8px;
}
🧠 How It Works:
display: flex
: Activates Flexbox layout.justify-content: center
: Centers items horizontally.align-items: center
: Centers items vertically.height: 100vh
: Makes the container full screen height (so vertical centering works).
✅ Center Multiple Items in a Column
You can also center multiple items vertically stacked in the center:
.container {
display: flex;
flex-direction: column; /* Stack items vertically */
justify-content: center;
align-items: center;
height: 100vh;
}
This is perfect for login pages, hero sections, or welcome screens.
🪄 One-Line Shortcut with place-content
(Grid Alternative)
If you prefer CSS Grid, there’s a one-line shorthand:
display: grid;
place-items: center;
But for Flexbox, the two properties justify-content
and align-items
are required.
📱 Responsive Considerations
For smaller screens:
- Ensure the container doesn’t overflow.
- Use media queries to adjust padding or height.
- Consider scrollable content if centering isn’t practical on short viewports.
📝 Conclusion
Vertically and horizontally centering elements is one of the most common layout needs—and Flexbox makes it effortless. With just display: flex
, justify-content: center
, and align-items: center
, your content is centered cleanly and responsively.
🔑 Quick Summary:
Task | CSS Code |
---|---|
Horizontal Center | justify-content: center; |
Vertical Center | align-items: center; |
Both | Combine both with display: flex |
Full Page Centering | Add height: 100vh to container |