Notes on flex-grow, flex-shrink, and flex-basis

Just a guy who loves to write code and watch anime.
Search for a command to run...

Just a guy who loves to write code and watch anime.
No comments yet. Be the first to comment.
Qualities that make outstanding builders.

Bipedal vs quadrupedal: how many legs This is about the number of legs the creature walks on. Bipedal. Two legs. Humans, ostriches, T-rex, kangaroos, most fantasy humanoids. Quadrupedal. Four legs. Do

Intro You hear "lerp" and "smoothstep" everywhere in game dev. They sound like math jargon. They're not. Both are small tools that do the same job: smoothly move from one value to another. The problem

What is Kinematics Kinematics is the math field. It's the study of how things move without worrying about forces (which would be dynamics). FK and IK are the two branches: forward kinematics and inver

Intro Textures are usually the biggest cost in a 3D scene. Memory, bandwidth, and load time all get eaten by them. Resizing them is the obvious lever. There's more. This post is about the less obvious

flex: 1 1 300px;
/* │ │ │
│ │ └── flex-basis (starting size)
│ └──── flex-shrink (how much it can shrink)
└────── flex-grow (how much it can grow)
*/
Most people use the shorthand (flex: 1) but the three-value version gives you way more control.
.item-a { flex: 2 0 100px; } /* gets 2x the extra space */
.item-b { flex: 1 0 100px; } /* gets 1x the extra space */
If there's 300px of extra space, item-a gets 200px and item-b gets 100px. Both start at 100px, then grow proportionally.
.sidebar { flex: 0 0 200px; } /* never shrinks */
.main { flex: 1 1 0; } /* shrinks first */
When space is tight, items with higher shrink values give up space first. flex-shrink: 0 means "never shrink, ever."
flex: 1 1 0; /* start from 0, distribute all space equally */
flex: 1 1 auto; /* start from content size, distribute leftover */
flex: 1 1 200px; /* start from 200px, then grow/shrink from there */
Basis isn't "width", it's more like "ideal size before flexing happens."
Flex items have min-width: auto by default, meaning they won't shrink below their content size. This breaks layouts:
/* Broken -> long text will overflow */
.flex-item { flex: 1; }
/* Fixed -> allows shrinking below content */
.flex-item { flex: 1; min-width: 0; }
/* Equal columns */
.col { flex: 1; min-width: 0; }
/* Fixed sidebar, flexible main */
.sidebar { flex: 0 0 200px; }
.main { flex: 1; min-width: 0; }
/* Responsive cards */
.card { flex: 1 1 300px; }
/* Grow only, never shrink */
.item { flex: 1 0 auto; }