Skip to content Skip to sidebar Skip to footer

Two Columns, And When One Is Hidden, The Other Expands The Full Width

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 the other to take up 100% width? I'm

Solution 1:

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;
}
<divclass="container"><divclass="box box1"></div><divclass="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:


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.

Post a Comment for "Two Columns, And When One Is Hidden, The Other Expands The Full Width"