Make flex-grow expand items based on their original size

前端 未结 4 2021
再見小時候
再見小時候 2020-11-22 12:07

I have 3 buttons in a row which all vary in width. I want them to all gain width the same to fill the remaining width of the row, so the widest will still be wider than the

4条回答
  •  太阳男子
    2020-11-22 12:51

    Minimalistic answer with (hopefully useful, explanatory) alternatives:

    HTML:

    
    

    CSS:

    .row-flex {
      display: flex;
    }
    
    .button {
      flex-grow: 1; /* make the item grow proportionally to its original size */
                    /* default value is 0, the item does not grow */
                    /* a meaningful default for flexbox items positioning with */
                    /* justify-content: ; */      
      padding: 10px;
      color: #fff;
      text-align: center;
    }
    
    .button--1 {
      background: red
    }
    
    .button--2 {
      background: green;
    }
    
    .button--3 {
      background: blue;
    }
    

    The following CSS declarations also work because all they do is override the default flex-grow: 0; to the (for the desired behavior required) flex-grow: 1;:

    .button {
      flex: auto;
      ...
    }
    

    which is a shorthand for:

    .button {
      flex: 1 1 auto;    
      ...
    }
    

    which is a shorthand for:

    .button {
      flex-grow: 1;
      flex-shrink: 1;
      flex-basis: auto;
      ...
    }
    

提交回复
热议问题