flex
A shorthand that sets an item’s flex-grow, flex-shrink, and flex-basis.
- Initial value
0 1 auto- Inherited
- No
- Animatable
- yes, numbers and length
- Applies to
- flex items
- JavaScript
element.style.flex = "1"
Example
#.app {
display: flex;
gap: 12px;
}
.app .sidebar { flex: 0 0 160px; }
.app .content { flex: 1; }<div class="app stage">
<aside class="sidebar box">Menu</aside>
<main class="content box">Lesson content fills the rest of the space</main>
</div>Definition and usage
#The flex property combines three flex-item properties: the ability to grow (flex-grow), to shrink (flex-shrink), and the base size (flex-basis). It’s the most common way to control item sizes in Flexbox.
It’s worth memorizing a few ready-made patterns. flex: 1 gives equal columns that split up all the space (1 1 0%). flex: auto lets an item grow and shrink from the size of its content (1 1 auto). flex: none freezes an item at its natural size (0 0 auto).
The shorthand sets more sensible defaults than the individual properties: when you give just a number, flex-basis becomes 0% rather than auto.
Syntax
#flex: none | auto | <flex-grow> <flex-shrink>? <flex-basis>?;Values
#initial
The default value: sized from content, with no growing.- All items are equally wide, regardless of their content.
- Items grow, but starting from the size of their content, so longer ones are wider.
- Item 2 neither grows nor shrinks, the rest share the remaining space.
- Item 2 is twice as wide as the others, which have
flex: 1.
Values in practice
#0 1 auto
.demo .box { flex: 0 1 auto; }1
.demo .box { flex: 1; }auto
.demo .box { flex: auto; }none
.demo .box { flex: 1; }
.target { flex: none; }2
flex: 1..demo .box { flex: 1; }
.target { flex: 2; }Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Remember three patterns:
flex: 1(equal shares),flex: auto(from content), andflex: none(no size change). - Use the shorthand instead of the three separate properties. You’ll avoid surprises with the default
flex-basis.
Related entries
#- Flexbox vs GridFlexbox lays out items along one dimension and sizes to their content. Grid defines a two-dimensional grid of rows and columns that you place items into.
- flex-growDetermines how eagerly an item grows to fill free space.
- flex-shrinkDetermines how much an item shrinks when the container runs out of room.
- flex-basisSets a flex item’s starting size on the main axis, before it grows or shrinks.
- displayDetermines how an element behaves in the page layout and how it lays out its children.
Spotted a mistake or missing an example? Write to us.