parliament parliament - 2 months ago 5x
CSS Question

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

on one of the divs, causes the other to take up 100% width?

I'm looking for a solution where I need to only change css on one of the elements for the other to take up the rest of the space.


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>


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.



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.