π¦ CSS Flexbox Tutorial: flex
π Introduction
The flex property is a powerful shorthand used on flex items inside a flex container. It combines three important properties:
- flex-grow β How much the item can grow
- flex-shrink β How much the item can shrink
- flex-basis β The initial size of the item
Using flex makes your code cleaner and easier to manage. π
β¨ Syntax
Syntax
selector {
flex: <flex-grow> <flex-shrink> <flex-basis>;
}Note
You donβt need to set all three values every time β CSS provides useful shortcuts.
π§© How flex Works
1. Full Longhand Form
Best for full control.
Longhand flex
.item {
flex: 1 1 200px;
}Meaning:
- 1 β can grow
- 1 β can shrink
- 200px β initial width (or height in column-direction)
π₯ Common Shorthand Variants
1. flex: 1
Makes the item grow to fill leftover space equally.
flex:1
.item { flex: 1; }Note
Equivalent to:
flex: 1 1 0;2. flex: 0
Item will not grow or shrink.
Code Snippet
.item { flex: 0; }3. flex: auto
Item grows and shrinks normally based on content size.
Code Snippet
.item { flex: auto; }Note
Equivalent to:
flex: 1 1 auto;4. flex: none
Completely inflexible, like a fixed-size element.
Code Snippet
.item { flex: none; }Note
Equivalent to:
flex: 0 0 auto;π₯ Practical Examples
1. Equal Width Columns
Equal Columns
.container {
display: flex;
}
.item {
flex: 1;
}2. Sidebar + Main Layout
Sidebar Layout
.container {
display: flex;
}
.sidebar {
flex: 0 0 250px; /* fixed */
}
.main {
flex: 1; /* fluid */
}3. Flex Items with Different Weights
Code Snippet
.item1 { flex: 1; }
.item2 { flex: 2; } /* twice as large as item1 */4. Prevent Shrinking
Code Snippet
.item {
flex: 1 0 200px; /* grows, no shrink */
}5. Responsive Cards
Code Snippet
.card {
flex: 1 1 250px; /* grow, shrink, minimum width */
}π flex Shorthand Cheat Sheet
| Shorthand | Expands To | Meaning |
|---|---|---|
| flex: 1 | 1 1 0 | Fully flexible item |
| flex: auto | 1 1 auto | Flexible, based on content |
| flex: none | 0 0 auto | No grow, no shrink |
| flex: 0 1 200px | grow:0, shrink:1, basis:200px | Fixed base size, shrink allowed |
π§ Tips & Best Practices
- Use flex: 1 for equal-size items
- Use flex-basis instead of width for better responsive behavior
- Use flex: none for buttons and fixed UI components
- Combine with
gapfor clean spacing
>>βflex gives you power β flex-basis gives you control. Together, you build perfect layouts.β β¨
π Conclusion
The flex shorthand is one of the most important tools in modern CSS layout design. It combines growth, shrinking, and size rules into a single, elegant property. Mastering it makes Flexbox layouts simpler, cleaner, and far more powerful. π