Currently, I have successfully coded a layout using Grid, but now I am looking to achieve the same layout using FlexBox due to compatibility issues with IE-11. Unfortunately, IE-11 does not support Grid properly.
Let's simplify things and focus only on xs
screens. Imagine that I have 6 cards:
<div class="container">
<div class="card1"> card 1 </div>
<div class="card2"> card 2 </div>
<div class="card3"> card 3 </div>
<div class="card4"> card 4 </div>
<div class="card5"> card 5 </div>
<div class="card6"> card 6 </div>
</div>
I want the structure to be flexible so that I can add or remove cards dynamically, and the layout adjusts automatically based on the number of cards present.
The default size of each card should match its container's width. For instance, if there is only one card, it should occupy the full width.
<div class="container">
<div class="card1"> card 1 </div>
</div>
If there are two cards, the width should be divided between them equally, similar to using flex-grow
.
<div class="container">
<div class="card1"> card 1 </div>
<div class="card2"> card 2 </div>
</div>
However, I encounter an issue with flex-grow
as I cannot control how the cards are stacked. In the case of having 6 cards on an xs
screen, I want them to form 3 rows with 2 cards in each row, which cannot be achieved solely with flex-grow
.
For medium-sized screens, I would like the cards to be displayed in 2 rows of 3 cards each. And for xs
screens, the layout should consist of 3 rows with 2 cards in each row.
I understand that FlexBox is one directional, but perhaps there are tricks or tips that I am not aware of. You can view my codepen example at https://codepen.io/jamie-jamier/pen/yLewWqy. However, please note that it does not fully meet my requirements. When you resize the screen to 500px
, you'll notice that the use of flex-wrap
results in displaying one card per row.