Chuck's Academy

Flexbox in CSS

Flex Property and Shorthand

The flex property is a shorthand property that encompasses three individual properties: flex-grow, flex-shrink, and flex-basis. Using the flex property can simplify your CSS, as it allows you to define in one go the growth, shrinkage, and base size behavior of flex items.

Syntax of the flex Property

The flex property is expressed as follows:

css

Values for the flex Property

  1. Auto: The default value. Equivalent to flex: 1 1 auto;, where the item can grow, shrink, and has an automatic base.

    css
  2. None: Equivalent to flex: 0 0 auto;, where the item does not grow or shrink and has an automatic base.

    css
  3. Flex-grow only: If you specify only one value, it will be interpreted as the value for flex-grow, with flex-shrink assumed to be 1 and flex-basis to be 0.

    css
  4. Custom values: You can specify all three values based on your needs.

    css

Example Usage of the flex Property

flex: auto

css
html

desktop-image: Placeholder: Image showing a row of flex items growing and shrinking automatically

flex: none

css
html

desktop-image: Placeholder: Image showing a row of flex items with rigid sizes

flex: 2

css
html

desktop-image: Placeholder: Image showing a row of flex items with the second item growing twice as much as the others

flex: 1 0 100px

css
html

desktop-image: Placeholder: Image showing a row of flex items with the second item having a different base

Complete Example with Different flex Property Configurations

html

desktop-image: Placeholder: Image showing the row with different configurations of flex: auto, none, grow 2, and custom

Summary

  • flex: Shorthand property to define the growth (flex-grow), shrinkage (flex-shrink), and base size (flex-basis) behavior of flex items.
  • Common values:
    • auto: flex: 1 1 auto;
    • none: flex: 0 0 auto;
    • Single number: Interpreted as flex-grow.
    • Custom values: Define specific flex-grow, flex-shrink, and flex-basis.

Using the flex property allows you to simplify your CSS and directly define how elements within a Flex container should behave regarding space distribution, growth, and shrinkage. This will enable you to create more efficient and organized layouts.


Ask me anything