Reputation: 785
I have set the parent div and its 3 children divs. Now, the 3rd child is hidden. I've set the width of the 1st child as 20% and wants the 2nd child to take the remaining width automatically without setting it explicitly. The 3rd child's width is 20% and when it's unhidden it should take its part of the parent's width while the 2nd should re-adjust its width accordingly.
<div id="parent" style="background-color: pink;">
<div id="child1" style="background-color: gray; display: inline-block; width: 20%;">
div1
</div>
<div id="child2" style="background-color: blue; display: inline-block">
div2
</div>
<div id="child2" style="background-color: violet; display: hidden; width: 20%;">
div3
</div>
</div>
Upvotes: 0
Views: 1798
Reputation: 16226
This can be implemented by flex layout. Here is the code snippet for your case:
#parent {
display: flex;
flex-direction: row;
}
#child1 {
flex-basis: 20%;
}
#child2 {
flex: 1;
}
#child3 {
display: none;
}
<div id="parent" style="background-color: pink;">
<div id="child1" style="background-color: gray;">
div1
</div>
<div id="child2" style="background-color: blue;">
div2
</div>
<div id="child3" style="background-color: violet;">
div3
</div>
</div>
Some explanation:
#parent
's display as flex
, start flex layout for all child elements.flex-direction
as row
, make child elements displayed horizontally.#child2
's flex
as 1
, which means it will shrink or extend to occupy all available space in #parent
.Please note all inline display
CSS rules are removed. They are not necessary once flex layout is enabled.
Upvotes: 5