0
0
CssHow-ToBeginner · 3 min read

How to Use flex-shrink in CSS: Simple Guide and Examples

The flex-shrink property in CSS controls how much a flex item will shrink relative to others when the flex container is too small. It accepts a number value where 0 means the item will not shrink and higher numbers allow more shrinking.
📐

Syntax

The flex-shrink property accepts a single number value that sets the shrinking factor of a flex item.

  • flex-shrink: 0; means the item will not shrink.
  • flex-shrink: 1; (default) means the item can shrink if needed.
  • Higher numbers like 2 mean the item shrinks twice as much as items with 1.
css
flex-shrink: <number>;
💻

Example

This example shows three boxes inside a flex container. The first box has flex-shrink: 0; so it won't shrink. The second and third boxes have flex-shrink: 1; and flex-shrink: 2; respectively, so the third box shrinks twice as much as the second when the container is smaller.

css
html, body {
  margin: 0;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f0f0f0;
}
.container {
  display: flex;
  width: 300px;
  border: 2px solid #333;
  padding: 10px;
  gap: 10px;
  background: white;
}
.box {
  background: #4a90e2;
  color: white;
  padding: 20px;
  font-weight: bold;
  text-align: center;
  min-width: 80px;
}
.box1 {
  flex-shrink: 0;
}
.box2 {
  flex-shrink: 1;
}
.box3 {
  flex-shrink: 2;
}
Output
Three blue boxes side by side inside a white container with a border. The first box stays full width, the second shrinks moderately, and the third shrinks the most when the container is narrow.
⚠️

Common Pitfalls

One common mistake is setting flex-shrink to 0 on all items, which can cause overflow if the container is too small. Another is forgetting that flex-shrink only works when the container is smaller than the total size of the items. Also, flex-shrink works with the flex-grow and flex-basis properties to control item sizing.

css
/* Wrong: all items won't shrink, causing overflow */
.container {
  display: flex;
  width: 200px;
}
.item {
  flex-shrink: 0;
  width: 150px;
  background: tomato;
  color: white;
  padding: 10px;
  margin-right: 5px;
}

/* Right: allow shrinking to fit container */
.item {
  flex-shrink: 1;
}
📊

Quick Reference

  • flex-shrink: 0; - Prevents shrinking.
  • flex-shrink: 1; - Default, allows shrinking equally.
  • flex-shrink: 2; - Shrinks twice as much as 1.
  • Works only when container is smaller than items.
  • Use with flex-grow and flex-basis for full control.

Key Takeaways

Use flex-shrink to control how much a flex item shrinks when space is tight.
flex-shrink: 0; stops an item from shrinking, which can cause overflow if overused.
Higher flex-shrink values make items shrink more compared to others.
flex-shrink only works when the container is smaller than the total flex items.
Combine flex-shrink with flex-grow and flex-basis for flexible layouts.