Two columns, and when one is hidden, the other expands the full width

后端 未结 1 422
-上瘾入骨i
-上瘾入骨i 2021-01-14 01:45

Is there a way with pure css to make 2 divs take up 50% width, and then setting a css property such as display:none on one of the divs, causes

相关标签:
1条回答
  • 2021-01-14 02:15

    What you're looking for is the flex-grow property, which tells elements in a flex container to occupy available space.

    So when there are two elements on one line, they will take as much space as they can, ultimately compromising 50/50. But if one element is removed, the other will automatically consume the remaining space.

    .container {
        display: flex;
    }
    
    .box {
        flex-grow: 1;  /* key rule */
        height: 50px;
        border: 1px solid #aaa;
    }
    
    .box1 {
        /* display: none; */
        background-color: aqua;
    }
    
    .box2 {
        /* display: none; */
        background-color: red;
    }
    <div class="container">
        <div class="box box1"></div>
        <div class="box box2"></div>
    </div>

    jsFiddle

    Applying flex-grow: 1 (or flex: 1) to a flex container's children ("flex items") tells them to distribute available space evenly among themselves.

    With flex-grow: 1:

    • Four flex items consume 25% each
    • Three items = 33.33%
    • Two items = 50%
    • One item = 100%

    Anytime an item is removed, the others will distribute the available space among themselves.

    Also read about the flex property, as the spec makes the following recommendation:

    Authors are encouraged to control flexibility using the flex shorthand rather than with flex-grow directly, as the shorthand resets any unspecified components to accommodate common uses.

    source: https://www.w3.org/TR/css-flexbox-1/#propdef-flex-grow


    References:

    • flex-grow property definition ~ MDN
    • flex-grow property definition ~ CSS-Tricks
    • 7.1. The flex-grow Shorthand ~ W3C

    Browser support:

    Flexbox is supported by all major browsers, except IE 8 & 9. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to generate prefixes use Autoprefixer. More details in this answer.

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