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
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>
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
:
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 withflex-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.