The meaning and benefits of flex: 1

后端 未结 3 932
清酒与你
清酒与你 2020-12-07 05:14

I stumbled upon flex: 1 today in some code and googled it to get some information about what it does. w3schools succinctly states:

Let al

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 05:51

    flex: 1 is short for flex: 1 1 0, and is one of the four flex values that represent most commonly-desired effects:

    • flex: initial - Equivalent to flex: 0 1 auto.
    • flex: auto - Equivalent to flex: 1 1 auto.
    • flex: none - Equivalent to flex: 0 0 auto.
    • flex: - Equivalent to flex: 1 0.

    Source:

    • https://www.w3.org/TR/css-flexbox-1/#flex-common

    flex: 1 1 0 is the shorthand for flex-grow: 1; flex-shrink: 1; flex-basis: 0;

    flex-grow: 0; flex-shrink: 1; flex-basis: auto;, or using the shorthand, flex: 0 1 auto, is the default value for a flex item.


    When it comes to useful cases, a list would be too long, so below is two samples, where the first show how one can make one flex item take the remaining space, and push the other to the right.

    .flex-container {
      display: flex;
    }
    
    .flex-item {
      background: lightgreen;
    }
    
    .flex-item.fill-remaining-space {
      flex: 1;
      background: lightblue;
    }
    Hey there.
    This item will be pushed to the right.

    And the second how 3 items share the space in their parent equal, regardless of their own content.

    .flex-container {
      display: flex;
    }
    
    .flex-item {
      flex: 1;
      border: 1px solid black;
    }
    Hey there.
    This item is wider.
    This item is the widest of all.

提交回复
热议问题