Flexbox Child Properties: Flex-Grow, Flex-Shrink, and Flex-Basis

Give Your Flex Items Some Superpowers!

So, you've mastered Flexbox containers—but what about the flex items inside them? If you want precise control over how items grow, shrink, or start, then you need to understand three magic properties:

  • flex-grow – Makes an item expand when there’s space.
  • flex-shrink – Allows an item to shrink when necessary.
  • flex-basis – Sets the starting size of an item.

By combining these three, you can create responsive, flexible layouts without breaking a sweat! 

Flex-Grow: Let Items Expand When Needed

The flex-grow property controls how much an item expands when there’s extra space in the container.

Syntax:

.item {
  flex-grow: 1;
}

How It Works:

  • flex-grow: 0; → The item does not grow (default behavior).
  • flex-grow: 1; → The item grows to take available space.
  • Higher numbers mean more growth!

Example:

.container {
  display: flex;
}
.item {
  flex-grow: 1;
  padding: 20px;
  background: lightblue;
}
<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>

Now, each item grows equally and fills the container!

Flex-Shrink: Allow Items to Shrink When Necessary

The flex-shrink property controls how much an item shrinks when space is tight.

Syntax:

.item {
  flex-shrink: 1;
}

How It Works:

  • flex-shrink: 0; → The item does not shrink (stays its size).
  • flex-shrink: 1; → The item shrinks when needed.
  • Higher numbers mean more shrinking!

Example:

.container {
  display: flex;
}
.item:nth-child(1) {
  flex-shrink: 0; /* Won't shrink */
}
.item:nth-child(2) {
  flex-shrink: 1; /* Shrinks normally */
}

This ensures that some items stay big while others shrink when space runs out!

Flex-Basis: Set the Initial Size of an Item

The flex-basis property defines the starting size of a flex item, before it grows or shrinks.

Syntax:

.item {
  flex-basis: 200px;
}

How It Works:

  • flex-basis: auto; → Uses the item’s natural width/height.
  • flex-basis: 50%; → Starts at 50% of the container.
  • flex-basis: 200px; → Starts at 200px wide.

Example:

.container {
  display: flex;
}
.item {
  flex-basis: 150px;
}

Now, each item starts at 150px before growing or shrinking!

Shortcut: The Magic flex Property!

Instead of writing three properties separately, you can use flex shorthand:

Syntax:

.item {
  flex: flex-grow flex-shrink flex-basis;
}

Example:

.item {
  flex: 1 1 200px; /* Grow, shrink, start at 200px */
}

This makes writing Flexbox properties faster and easier!

Conclusion

  • Flex-Grow → Expands an item when there’s extra space.
  • Flex-Shrink → Shrinks an item when space is limited.
  • Flex-Basis → Defines the item’s starting size.
  • Use the flex shorthand for quick styling!

Build ultra-responsive layouts with ease!

Post a Comment

0 Comments