CSS flex, how to select the last item of each row?

479 Views Asked by At

As explained below, this question is NOT a duplicate of this question. Please, read carefully before marking it as duplicate.

I already read carefully this question which is similar, except he wants to select the items of the last row. Here I want to select the last item of each row.

Is there a way to select the last item of each row in a flex arrangement (without JavaScript)? On the following example, I would like a CSS selector that selects div 5 and 10 (and eventually 12).

Flex example

Of course, it has to be responsive.

  • Solutions like :nth-child(5) will not select the right div if the window is resized.
  • Divs have variable widths.

I already read carefully this question which is similar, except he wants to select the items of the last row. Here I want to select the last item of each row.

Since there is no proper solution to the question above, I'm afraid that what I want to do is impossible without JavaScript.

Here is a JSFidle used to generate the above image.

#container {
    background-color: LightSteelBlue;   
    
    width: 100%;
    height: fit-content;
    flex-wrap: wrap;
    display: flex;
    justify-content: space-between; 
    /*justify-content: stretch;*/
}

.child {
    font-family: 'Monoton', cursive;
    
    color: white;
    font-size: 40px;
    display : flex;
    align-items : center;
    justify-content: center;
    
    width: 100px;
    height: 100px;
    margin: 10px;
    background-color: SteelBlue;
    
    border: 1px solid black;
    flex-grow: 1;
}

#container::after {
    /*background-color: red;*/
    content: "";    
    flex-grow: 100;
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Gajraj+One&family=Monoton&family=Righteous&display=swap" rel="stylesheet">

<div id="container">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>  
    <div class="child">4</div>  
    
    <div class="child">5</div>
    <div class="child">6</div>
    <div class="child">7</div>  
    <div class="child">8</div>  
    
    <div class="child">9</div>
    <div class="child">10</div>
    <div class="child">11</div> 
    <div class="child">12</div> 
</div>

1

There are 1 best solutions below

4
DullJoker On

you could run something like this:

.wrapper {
  display: flex;
  flex-wrap: wrap;
}

.item {
  width: calc((100% - 2*10px)/5);
  height: 50px;
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 5px;
  box-sizing: border-box;
}

// last item of each row
.elem:nth-child(5n) {
  margin-right: 0;
}

// last 3 items
.elem:nth-last-child(-n+5){
  margin-bottom: 0;
}

In this example you can replace the 5nth for anything you want to specify the amount of elements per row.