CSS

Controlling Flex Item Growth and Shrinkage

Understand how `flex-grow`, `flex-shrink`, and `flex-basis` control the allocation of space among flex items, allowing precise layout adjustments for responsiveness.

.flex-container {
    display: flex;
    width: 600px; /* For demonstration */
    border: 1px solid #000;
    padding: 10px;
}
.flex-container > div {
    padding: 20px;
    text-align: center;
    border: 1px solid #ccc;
    margin: 5px;
}
.item-a {
    flex: 1 1 100px; /* grows 1, shrinks 1, initial basis 100px */
    background-color: lightblue;
}
.item-b {
    flex: 2 0 150px; /* grows 2 (twice as much as A), doesn't shrink, initial basis 150px */
    background-color: lightgreen;
}
.item-c {
    flex: 0 1 auto; /* doesn't grow, shrinks 1, initial basis auto (content size) */
    background-color: lightcoral;
}
/* HTML Structure Example: */
/* <div class="flex-container">
/*   <div class="item-a">Item A</div>
/*   <div class="item-b">Item B</div>
/*   <div class="item-c">Item C</div>
/* </div> */
How it works: The `flex` shorthand property (or `flex-grow`, `flex-shrink`, `flex-basis` individually) defines how a flex item will grow or shrink to fit the available space in its flex container. `flex-grow` (first value) dictates how much an item will grow relative to others if there's extra space. `flex-shrink` (second value) controls shrinkage if there isn't enough space. `flex-basis` (third value) sets its initial size before any growing or shrinking occurs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs