I have a parent div, that at least contains one child. In some cases it will contain 2 children and in the last case it will contain 3 children. I would like to achieve that in all three cases the children expand to the 100% width.
Case1 Here childrenA should be width:100%
<div >
<div ></div>
</div>
Case2 Here childrenA should be width:50% and childrenB should be width:50%
<div >
<div ></div>
<div ></div>
</div>
Case3 Here childrenA should be width:33%, childrenB should be width:33% and childrenC should be width:33%
<div >
<div ></div>
<div ></div>
<div ></div>
</div>
CodePudding user response:
Yeah width can be set automatically with the help of flex box assuming the height of the child elements is specified;
on Parent div
.parent {
display:flex;
}
assuming the height of children divs to be 100px,we can do
.childrenA{
background-color:violet;
height:100px;
flex:1;
}
.childrenB{
background-color:grey;
height:100px;
flex:1;
}
.childrenC{
background-color:green;
height:100px;
flex:1;
}
flex:1 is a shorthand for
flex-grow : 1; ➜ The div will grow in same proportion as the window-size
flex-shrink : 1; ➜ The div will shrink in same proportion as the window-size
flex-basis : 0; ➜ The div does not have a starting value as such and will
take up screen as per the screen size available for
e.g:- if 3 divs are in the wrapper then each div will take 33%.
.childrenA {
background-color: violet;
height: 100px;
flex: 1;
}
.childrenB {
background-color: grey;
height: 100px;
flex: 1;
}
.childrenC {
background-color: green;
height: 100px;
flex: 1;
}
.parent {
display: flex;
}
<div >
<div ></div>
</div>
<br>
<div >
<div ></div>
<div ></div>
</div>
<br>
<div >
<div ></div>
<div ></div>
<div ></div>
</div>