The flex property
flex is set on a flex item and defines how it shares space with its siblings: whether it grows, whether it shrinks and what size it starts from.
Syntax
flex: none | auto | <number> | <flex-grow> <flex-shrink> <flex-basis>;
flex: 1; /* 1 1 0% */
flex: 1 1 220px; /* grows, shrinks, base 220px */ - Initial value
0 1 auto- Inherited
- no
- Applies to
- flex items (direct children of a flex container)
Values
| Value | What it does |
|---|---|
none | 0 0 auto: does not grow or shrink — sized to its content |
auto | 1 1 auto: grows and shrinks starting from its content size |
<number> | one number is a share of the free space: flex: 1 means 1 1 0%, and items with the same number get the same width |
<grow> <shrink> <basis> | the three values separately: flex-grow, flex-shrink and flex-basis |
Example
.row {
display: flex;
gap: 8px;
}
.row div {
padding: 12px;
background: #e0f2fe;
border: 1px solid #0284c7;
}
.a { flex: 1; }
.b { flex: 2; }
.c { flex: none; } <div class="row">
<div class="a">flex: 1</div>
<div class="b">flex: 2</div>
<div class="c">flex: none</div>
</div> Result
Good to know
- flex is set on items, not on the container: the container needs display: flex.
- flex: 1 and flex: auto differ: with 1 the base size is 0 and the width is shared equally; with auto the content width is taken first.
- A flex item's minimum width is the width of its content, so a long word stops it from shrinking. min-width: 0 helps.
Sources and specification
- MDN: flex — MDN Web Docs
- CSS Flexible Box Layout Module Level 1 (W3C) — W3C
See also
The gap property
The CSS gap property sets the space between items of a flex or grid container without extra margins: one or two values, row-gap and column-gap.
The justify-content property
CSS justify-content distributes space between items along the main axis in flexbox and grid: flex-start, center, space-between, space-evenly.
The display property
The CSS display property sets how an element takes part in layout: as a block, inline with text, as a flex or grid container, or not at all. Values, examples.
CSS Flexbox Playground
Change flex-direction, justify-content, align-items, flex-wrap and gap and see how flexbox works right away. Copy the ready CSS code in one click.
CSS Flexbox for beginners
A beginner's guide to CSS Flexbox: display: flex, axes, justify-content, align-items, flex-wrap, gap and flex: 1, with examples of a menu, cards and centering.
Flexbox: header menu and a row of cards
Flexbox practice exercise: put the logo and menu side by side in the header and line course cards up in an equal-height row that wraps on narrow screens.