CSS flex Property

Subject: css

CSS flex Property

The flex property in CSS is a shorthand that controls how a flex item behaves inside a flex container. It combines three properties:

  • flex-grow
  • flex-shrink
  • flex-basis

Syntax

You can provide one, two, or all three values depending on your use case.


Why Use flex?

  • Efficiently distribute space among items
  • Control how items grow or shrink
  • Create responsive layouts with less code
  • Eliminate need for float-based or width-heavy design

Example 1: Equal Space Distribution

Result: All items equally share the available horizontal space.


Example 2: Custom Growth with flex: 2

This makes the first item take twice as much space as the others.


Example 3: Full Shorthand - flex: 1 0 150px

This means:

  • flex-grow: 1 – Item grows when space is available
  • flex-shrink: 0 – Item won’t shrink
  • flex-basis: 150px – Initial width is 150px

Best Practices

  • Use flex: 1 for equal item growth
  • Use flex: 0 1 auto to shrink but not grow
  • Use flex: none to prevent both growth and shrinking
  • Combine with min-width, max-width, or auto for fine control
  • Avoid hardcoding widths unless necessary

Key Takeaways

  • flex is a shorthand for flex-grow, flex-shrink, and flex-basis
  • Simplifies layout logic in Flexbox
  • Great for responsive layouts and dynamic item sizing
  • Enables equal or weighted distribution of space
  • Use intentionally with other Flexbox utilities for best results