This content originally appeared on DEV Community and was authored by Jyoutis
Once I gave Flexbox a real try, it finally clicked. I realized I only needed three lines of CSS to center elements both horizontally and vertically.
The Flexbox Formula to center anything inside a container using Flexbox:
Add display: flex to the parent container.
Use justify-content: center to center horizontally.
Use align-items: center to center vertically.
That’s it.
HTML
<div class="parent-element">
<div class="child-element">Child 1</div>
<div class="child-element">Child 2</div>
</div>
CSS
.parent-element {
background-color: #999;
border: 4px solid #000;
display: flex;
justify-content: center;
align-items: center;
height: 200px;
}
.child-element {
font-family: sans-serif;
font-size: 18px;
text-align: center;
color: #fff;
background-color: #1a8446;
padding: 3em;
margin: 7px;
}
What I Learned
display: flex
- turns the container into a flexbox.
justify-content: center
- aligns child elements horizontally (main axis).
align-items: center
aligns them vertically (cross axis).
Setting a height on the parent is necessary to see vertical centering.
What I’m Going to Try Next
Here’s what I’m curious to explore as I keep learning Flexbox:
- Play with flex-direction to see how it affects layout flow.
- Use gap instead of margins to space out elements (cleaner).
- Explore flex-wrap to understand how Flexbox behaves with multiple lines of content.
Let’s connect on LinkedIn—I’d love to network.
This content originally appeared on DEV Community and was authored by Jyoutis