I am currently working on a React project that involves displaying a set of cards inside a container. Each card has a fixed size of 231x237px. I have used flexbox for the layout of the cards. I want the number of columns to be even when moving a card to a new line. For example 2,4. Or 1 (on the smallest devices)
1 row: Card - Card - Card - Card
or
1 row: Card - Card
2 row: Card - Card
A different take on your issue is using css grid to achieve your layout behaviour.
Apply grid on your main section:
HTML:
<section>
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
</section>
Add CSS to the main div / section. Here you can specify the amount of columns @ grid-template-columns.
section {
max-width: 80%;
margin: 0 auto;
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
gap: 1rem;
}
And break the template column on your pref width
@media only screen and (max-width: 1440px) {
section {
grid-template-columns: 1fr 1fr;
}
}
@media only screen and (max-width: 640px) {
section {
grid-template-columns: 1fr;
}
}
See the working sample on my codepen