CSS flex Property

CSS flex Property

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

selector { flex: [flex-grow] [flex-shrink] [flex-basis]; }
ValueDescription
flex-growDefines how much an item expands to fill space.
flex-shrinkDefines how much an item shrinks when space is tight.
flex-basisDefines the initial size of the item.

2. Basic Example

✅ Default Flex (flex: 0 1 auto;)

.container { display: flex; } .item { flex: 0 1 auto; padding: 20px; background: lightblue; }

✅ Each item sizes based on content and shrinks if needed.

✅ Equal Flex Items (flex: 1;)

.item { flex: 1; }

✅ Each item expands equally to fill available space.

✅ Mixed Growth (flex: 2;)

.item:nth-child(2) { flex: 2; }

Second item grows twice as fast as others.

3. Example – Different flex Values

.container { display: flex; gap: 10px; } .item { padding: 20px; background: lightblue; text-align: center; } .item:nth-child(1) { flex: 1; } .item:nth-child(2) { flex: 2; } .item:nth-child(3) { flex: 1 2 150px; }
<div class="container"> <div class="item">1 (flex: 1)</div> <div class="item">2 (flex: 2)</div> <div class="item">3 (flex: 1 2 150px)</div> </div>

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 ValueEquivalent 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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close