Whenever I try to set up flex items this way, instead of getting 2 per row I am getting 4. But with the second solution it seems to work properly. Why it wont work as it is in first css code?
<div >
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
</div>
.container {
display: flex;
flex-wrap: wrap;
}
.item {
flex: 0.5;
}
Second:
.container {
display: flex;
flex-wrap: wrap;
}
.container > div {
flex: 50%;
}
CodePudding user response:
Having display flex, plus flex-wrap property. It will occupy based on the available space left covered the space.
Coming back to your question, flex is the shorthand for flex-grow, flex-shrink, and flex-basis. so having 0.5 will not be equal to 50%.
To understand more about the flex properties look at this for your references.
I usually opt for grid, when I need to show a particular amount of elements on a certain situation.
We can change the display from flex to grid:
display: grid;
grid-template-columns: 1fr 1fr;
CodePudding user response:
Flex is the shorthand for flex-grow, flex-shrink and flex-basis combined. The second and third parameters (flex-shrink and flex-basis) are optional. The default is 0 1 auto, but if you set it with a single number value, like flex: 5;, that changes the flex-basis to 0%, so it’s like setting flex-grow: 5; flex-shrink: 1; flex-basis: 0%;. Flex-grow is scalable. But if you want to scale the width as a percentage. Then you should use the percent sign to allow you to scale the width. This code is similar to:
.container {
display: flex;
flex-wrap: wrap;
}
.item {
flex: 50%;
}
<div >
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
</div>