CSS
Controlling Flex Item Sizing and Distribution with `flex` Shorthand
Learn to precisely control how flex items grow, shrink, and define their initial size using the `flex` shorthand property, creating dynamic and adaptive layouts easily.
.flex-container-sizing {
display: flex;
gap: 10px;
width: 100%;
border: 1px solid #ccc;
padding: 10px;
}
.flex-item-grow {
flex: 1 1 150px; /* grow: 1, shrink: 1, basis: 150px */
background-color: lightgreen;
padding: 15px;
text-align: center;
}
.flex-item-fixed {
flex: 0 0 100px; /* grow: 0, shrink: 0, basis: 100px */
background-color: lightyellow;
padding: 15px;
text-align: center;
}
.flex-item-auto {
flex: 1; /* Shorthand for flex: 1 1 0% */
background-color: lightsalmon;
padding: 15px;
text-align: center;
}
How it works: This snippet illustrates how to manage the size and flexibility of flex items using the `flex` shorthand property, which combines `flex-grow`, `flex-shrink`, and `flex-basis`. `flex-item-grow` elements are set to grow and shrink relative to their content, starting from a `150px` base. `flex-item-fixed` elements maintain a fixed `100px` width, neither growing nor shrinking. `flex-item-auto` (shorthand `flex: 1`) items will grow and shrink from a `0%` base, effectively distributing available space evenly among themselves.