CSS flex
Property
The flex
property in CSS is a shorthand for setting flex-grow
, flex-shrink
, and flex-basis
in one line. It controls how a flex item behaves inside a flex container.
1. Syntax
Value | Description |
---|---|
flex-grow | Defines how much an item expands to fill space. |
flex-shrink | Defines how much an item shrinks when space is tight. |
flex-basis | Defines the initial size of the item. |
2. Basic Example
✅ Default Flex (flex: 0 1 auto;
)
✅ Each item sizes based on content and shrinks if needed.
✅ Equal Flex Items (flex: 1;
)
✅ Each item expands equally to fill available space.
✅ Mixed Growth (flex: 2;
)
✅ Second item grows twice as fast as others.
3. Example – Different flex
Values
✅ Second item is twice as wide as the others.
✅ Third item starts at 150px but shrinks twice as fast.
4. Common flex
Shorthand Values
flex Value | Equivalent to |
---|---|
flex: 1; | flex: 1 1 0%; (Grows equally, shrinks equally, starts at 0) |
flex: 0 1 auto; (default) | Uses content size and shrinks if needed |
flex: 2; | flex: 2 1 0%; (Grows twice as fast as others) |
flex: none; | flex: 0 0 auto; (No grow, no shrink, uses natural size) |
5. Best Practices
✔ Use flex: 1;
for equal distribution of space.
✔ Use flex: 2;
or higher to prioritize certain items.
✔ Use flex: 0 0 auto;
for fixed-size items.