Make div fill remaining *horizontal* space in flexbox

前端 未结 2 788
情话喂你
情话喂你 2020-11-22 05:31

I have 2 divs side-by-side in a flexbox. The right hand one should always be the same width, and I want the left hand one to just grab the remaining space. But it won\'t unl

2条回答
  •  花落未央
    2020-11-22 05:41

    Use the flex-grow property to make a flex item consume free space on the main axis.

    This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

    A common example is flex-grow: 1 or, using the shorthand property, flex: 1.

    Hence, instead of width: 96% on your div, use flex: 1.


    You wrote:

    So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.

    The squashing of the fixed-width div is related to another flex property: flex-shrink

    By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container.

    To disable this feature use flex-shrink: 0.

    For more details see The flex-shrink factor section in the answer here:

    • What are the differences between flex-basis and width?

    Learn more about flex alignment along the main axis here:

    • In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

    Learn more about flex alignment along the cross axis here:

    • How does flex-wrap work with align-self, align-items and align-content?

提交回复
热议问题