Home > Software engineering >  Using Flexbox, can I change the amount of items displayed on a row, depending on how many items are
Using Flexbox, can I change the amount of items displayed on a row, depending on how many items are

Time:04-01

Scenario:

Using flexbox, I'm creating a template where the number of 'cards' displayed can change from page to page. If a user adds 2, 3 or 4 cards – the layout is great.

However, if a user adds 5 cards, the layout is now less aesthetically pleasing with the 5th card alone on a new row.

Is there a way I can display up to 4 cards on a row, but if there are 5 cards.. then the first row would display 3 cards, and the second row would display 2?

Here's a general idea of how the code would be displayed.

<style>
  .cards-wrapper {
    display: flex;
    flex-wrap: wrap;
  }
  
  .cards-wrapper .card {
    flex: 1 1 20%;
    margin: 10px;
  }
</style>

<div >

  <div > </div>

  <div > </div>

  <div > </div>

  <div > </div>

  <div > </div>

</div>

CodePudding user response:

You can combine nth-child & nth-last-child pseudo classes.

.cards-wrapper {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}
.cards-wrapper .card {
    flex: 1 1 calc(25% - 10px);
}
.card:nth-child(1):nth-last-child(5),
.card:nth-child(2):nth-last-child(4),
.card:nth-child(3):nth-last-child(3) {
    flex-basis: calc(33.333% - 10px);
}

The trick works for 5 elements (9th would stay alone in the last row) However, this is not elegant solution. In this case I'd recommend to use CSS grid instead of flexbox.

CodePudding user response:

This is what I would do. You can create two classes based on the number of items. Count the number of elements ( if you are using a backend language or also with javascript ). Making the layout automatically based on the items is usually done with the backend languages or javascript.

one with this (remove the margins)

flex: 0 1 33.3333%;

and one class with

flex: 0 1 25%;

You could also give them inline width based on the number of items.

CodePudding user response:

You can accomplish this with Bootstrap if you are able to use this. https://getbootstrap.com/docs/4.1/layout/grid/#all-breakpoints

Bootstrap comes with the breakpoints already defined so you give it the specific class you need based off the sizing of the screen col-lg-3 (on a large screen the column will span 3)

  • Related