TutsFx logo

CSS Flexbox Crash Course

Flex Items: grow, shrink and basis

1 min read Last updated 46 minutes ago

Flex items can grow to fill space, shrink to fit, or hold a fixed basis. The shorthand flex controls all three at once.

The three properties

css
.item {
    flex-grow: 1;     /* how much to grow relative to siblings */
    flex-shrink: 1;   /* how much to shrink when space runs out */
    flex-basis: 0;    /* the starting size before growing/shrinking */
}

The shorthand

css
.item {
    flex: 1;          /* grow:1 shrink:1 basis:0 */
}

flex: 1 is the workhorse of equal-width columns:

html
<div class="columns">
    <div class="column">A</div>
    <div class="column">B</div>
    <div class="column">C</div>
</div>
css
.columns {
    display: flex;
    gap: 1rem;
}
.column {
    flex: 1;
    padding: 1rem;
    background: #f5f6f7;
}

Keeping a sidebar fixed

Let one column grow while the other stays fixed:

css
.sidebar {
    flex: 0 0 240px;   /* don't grow, don't shrink, always 240px */
}
.main {
    flex: 1;
}
!

flex-basis gotcha

Remember that flex-basis respects the main axis. In a column layout, flex-basis behaves like height, not width.

The gap property

Modern flexbox supports gap for spacing between items:

css
.row {
    display: flex;
    gap: 1rem;   /* 1rem between every item */
}

No more negative margins on last-child.

Share:

We value your privacy

We use cookies to enhance your browsing experience, serve personalized ads, and analyze traffic. By clicking "Accept", you consent to our use of cookies. Read our Privacy Policy to learn more.