← Back to all snippets
CSS

Mastering Flex Item Sizing with flex-grow, flex-shrink, flex-basis

Gain precise control over how flex items distribute space, grow, and shrink within a flex container using the `flex` shorthand and its individual properties.

.flex-container {
  display: flex;
  width: 600px;
  border: 2px solid #333;
  padding: 10px;
  margin-bottom: 20px;
}

.flex-item {
  padding: 20px;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  margin: 5px;
  color: #555;
  font-family: sans-serif;
  text-align: center;
}

/* Item 1: Grows twice as much as others, never shrinks, starts at 100px */
.flex-item.one {
  flex: 2 0 100px; /* flex-grow: 2, flex-shrink: 0, flex-basis: 100px */
  background-color: lightcoral;
}

/* Item 2: Grows normally, shrinks normally, starts at 200px */
.flex-item.two {
  flex: 1 1 200px; /* flex-grow: 1, flex-shrink: 1, flex-basis: 200px */
  background-color: lightgreen;
}

/* Item 3: Never grows, shrinks normally, starts at 50px */
.flex-item.three {
  flex: 0 1 50px; /* flex-grow: 0, flex-shrink: 1, flex-basis: 50px */
  background-color: lightblue;
}

/* Common shorthands: */
/* flex: auto;   -> flex: 1 1 auto; (grow, shrink, base on content/auto) */
/* flex: initial; -> flex: 0 1 auto; (don't grow, shrink, base on content/auto) */
/* flex: none;    -> flex: 0 0 auto; (don't grow, don't shrink, base on content/auto) */
/* flex: <positive-number>; -> flex: <number> 1 0%; (e.g., flex: 1 is flex: 1 1 0%) */
How it works: This snippet details the powerful `flex` shorthand property and its individual components: `flex-grow`, `flex-shrink`, and `flex-basis`. `flex-grow` determines how much an item will grow relative to others when there's extra space. `flex-shrink` defines how much an item will shrink when there isn't enough space. `flex-basis` sets the initial size of the item before any growing or shrinking occurs. Understanding these properties provides fine-grained control over how flex items adapt to their container's available space.

Need help integrating this into your project?

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

Hire DigitalCodeLabs