CSS

Control Flex Item Growth/Shrink Ratios

Learn to manage how flex items expand or contract within their container using `flex-grow` and `flex-shrink` properties with custom ratios, ensuring adaptive sizing and precise space distribution.

.flex-container {
  display: flex;
  width: 100%;
  border: 1px solid #ccc;
  height: 100px;
}

.flex-item {
  padding: 10px;
  text-align: center;
  background-color: lightblue;
  margin: 5px;
  min-width: 50px; /* Prevent items from shrinking below a certain point */
}

.item-grow-double {
  flex-grow: 2; /* Grows at twice the rate of other items with flex-grow: 1 */
  flex-shrink: 1;
}

.item-fixed {
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 100px; /* Fixed width, won't grow or shrink */
  background-color: lightcoral;
}

.item-shrink-half {
  flex-grow: 1;
  flex-shrink: 0.5; /* Shrinks at half the rate of other items with flex-shrink: 1 */
  background-color: lightgreen;
}

/* HTML Structure */
<!--
<div class="flex-container">
  <div class="flex-item">Item 1</div>
  <div class="flex-item item-grow-double">Item 2 (Grow 2x)</div>
  <div class="flex-item item-fixed">Item 3 (Fixed)</div>
  <div class="flex-item item-shrink-half">Item 4 (Shrink 0.5x)</div>
</div>
-->
How it works: This snippet demonstrates how to control the distribution of available space among flex items using `flex-grow` and `flex-shrink` ratios. `flex-grow` determines how much a flex item will grow relative to the rest of the flex items when there's positive free space. A `flex-grow` of 2 means it will take up twice as much extra space as an item with `flex-grow` of 1. Conversely, `flex-shrink` dictates how much a flex item will shrink relative to others when there's negative free space. An item with `flex-shrink: 0.5` will shrink at half the rate of an item with `flex-shrink: 1`, making it more resistant to shrinking. `flex-basis` can be used to set an initial size, and `flex-grow: 0; flex-shrink: 0;` creates a fixed-size item.

Need help integrating this into your project?

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

Hire DigitalCodeLabs