Flex Item Sizing

Three properties control a flex item’s ability to dynamically adjust to it’s container:

  • flex-grow
  • flex-shrink
  • flex-basis

Or, use the flex shorthand property.

flex-basis

Sets the initial main size of a flex item. The initial value is set to auto or the size of the content.

flex-grow

Specifies the flex grow factor or how much an item will grow relative to the rest of the items in the container.

If all items have the same factor, then space will be evenly distributed between them.

flex-shrink

Specifies the flex shrink factor or how much an item will shrink relative to the rest of the items in the container.

Example

<div class="flex-container">

    <!-- flex items -->
    <div class="box" id="one">Box 1</div>
    <div class="box" id="two">Box 2</div>
    <div class="box" id="three">Box 3 Lorem ipsum dolor sit amet, consectetur adipiscing
            elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
            enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
            aliquip ex ea commodo consequat. Duis aute.</div>
    <div class="box" id="four">Box 4 Lorem ipsum dolor sit amet, consectetur adipiscing
        elit, sed do eiusmod tempor incididunt ut labore et dolore</div>
    <div class="box" id="five">Box 5</div>
</div>
.flex-container{
    display: flex;
}
.box {
    background-color: rgb(204, 172, 66);
    border: 1px solid rgb(131, 105, 21);
    padding: 1em;

    flex-grow: 1;
    flex-shrink: 1;
    flex-basis: 0;

    /* or the shorthand version

     flex: 1 1 0;

    */
}

#three {
    flex: 4 1 0;
}

#four {
    flex: 2 1 0;
}
In the above example, the box class is is given a grow factor of 1, a shrink factor of 1, and a basis of 0. All items will be treated the same and given equal consideration regardless of content.

We do however define a few exceptions for box three and four where the grow factor is increased just for these elements.

Download the lesson file and adjust the property values to see how the factors influence the layout.

Further Review

References