πŸ“¦ 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

ShorthandExpands ToMeaning
flex: 11 1 0Fully flexible item
flex: auto1 1 autoFlexible, based on content
flex: none0 0 autoNo grow, no shrink
flex: 0 1 200pxgrow:0, shrink:1, basis:200pxFixed 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 gap for 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. πŸš€