Flexbox not giving equal width to elements

前端 未结 2 1142
攒了一身酷
攒了一身酷 2020-11-28 00:28

Attempting a flexbox nav that has up to 5 items and as little as 3, but it\'s not dividing the width equally between all the elements.

Fiddle

The tutorial

相关标签:
2条回答
  • 2020-11-28 01:01

    There is an important bit that is not mentioned in the article to which you linked and that is flex-basis. By default flex-basis is auto.

    From the spec:

    If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)

    Each flex item has a flex-basis which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow) among the items. With auto, that basis is the contents size (or defined size with width, etc.). As a result, items with bigger text within are being given more space overall in your example.

    If you want your elements to be completely even, you can set flex-basis: 0. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow.

    li {
        flex-grow: 1;
        flex-basis: 0;
        /* ... */
    }
    

    This diagram from the spec does a pretty good job of illustrating the point.

    And here is a working example with your fiddle.

    0 讨论(0)
  • 2020-11-28 01:11

    To create elements with equal width using Flex, you should set to your's child (flex elements):

    flex-basis: 25%;
    flex-grow: 0;
    

    It will give to all elements in row 25% width. They will not grow and go one by one.

    0 讨论(0)
提交回复
热议问题