Here are some practical Flexbox tricks every modern frontend developer should know. Whether you’re building layouts, aligning items, or fixing responsiveness â Flexbox is your best friend.
đŠ Quick Refresher: What Is Flexbox?
Flexbox is a CSS layout module designed for one-dimensional layouts â arranging items in a row or column.
Just set the parent container to:
display: flex;
And you unlock a powerful layout system.
đ§ Key Flexbox Properties
Property | Applied To | Description |
---|---|---|
display: flex | Parent | Activates Flexbox |
flex-direction | Parent | row , column , row-reverse , etc. |
justify-content | Parent | Horizontal alignment |
align-items | Parent | Vertical alignment |
flex-wrap | Parent | Wrap items to new lines |
flex | Child | Defines grow/shrink/basis |
align-self | Child | Overrides parent align-items for one item |
đŻ Flexbox Tricks Youâll Actually Use
1. Center Anything (Horizontally & Vertically)
.parent {
display: flex;
justify-content: center;
align-items: center;
}
â Works for text, images, buttons, and more.
2. Equal-Width Columns
.column {
flex: 1;
}
<div class="flex">
<div class="column">1</div>
<div class="column">2</div>
<div class="column">3</div>
</div>
đŠ flex: 1
makes each item take equal space.
3. Responsive Wrapping Grid
.flex-grid {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.flex-item {
flex: 1 1 200px;
}
â Automatically wraps items and maintains min width.
4. Auto Margin Trick (Push Item to End)
.menu-item:last-child {
margin-left: auto;
}
â Great for pushing nav items (like Logout) to the far end.
5. Sticky Footer with Flex
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1;
}
â Makes the footer stick to the bottom if content is short.
6. Vertical Side Menu
.menu {
display: flex;
flex-direction: column;
align-items: flex-start;
}
â Perfect for vertical navigation layouts.
7. Vertical Divider Between Items
.container {
display: flex;
align-items: center;
}
.item:not(:last-child)::after {
content: '';
width: 1px;
height: 100%;
background: #ccc;
margin: 0 10px;
}
â Adds vertical dividers between flex items.
8. Reverse Order on Mobile
@media (max-width: 600px) {
.flex-container {
flex-direction: column-reverse;
}
}
â Easy way to reorder content without touching HTML.
9. Make One Item Fill Remaining Space
.item-grow {
flex-grow: 1;
}
â Useful in sidebars, toolbars, and header bars.
10. Perfect Card Grid with Wrap and Gap
.cards {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 1 1 calc(33.333% - 20px);
}
â Makes a responsive grid of 3 cards per row with spacing.
đ§Ș Bonus: Visual Tools for Flexbox
đ§ Flexbox Froggy â interactive game
đŻ CSS Tricks Flexbox Guide â visual reference
đ§° Flexy Boxes Generator â build layouts visually
â Summary
Goal | Trick |
---|---|
Center content | justify-content + align-items |
Equal columns | flex: 1 |
Responsive grid | flex-wrap + flex-basis |
Push item to right | margin-left: auto |
Sticky footer | flex: 1 on main content |