Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting nth-child of potentially infinite list of children

I have a grid layout - 4 columns per row. I am using CSS grid layout.

Say there could potentially be an infinite number of items.

<div class="grid">
    <div class="item"></div>
    <div class="item"></div>
    <!-- ... -->
</div>

How could I select the two middle items of each row if the number of items is potentially infinite. For example for the first three rows I would need to select:

nth-child(2), nth-child(3), nth-child(6), nth-child(7), nth-child(10), nth-child(11)

I could hard code the styles up to a specific number assuming there wouldn't be an infinite number, but if there's a way to do it dynamically I'd rather do that.

enter image description here

like image 963
pizzarob Avatar asked Jan 04 '23 10:01

pizzarob


2 Answers

You can use .item:nth-child(4n+2) to target every fourth child (start from 2'nd child) and .item:nth-child(4n+3) to target every fourth child (start from 3'rd child). Here is the example:

.item:nth-child(4n+2),
.item:nth-child(4n+3) {
  color: red;
  background-color: yellow;
}
<div class="grid">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
    <div class="item">10</div>
    <div class="item">11</div>
    <div class="item">12</div>
</div>
like image 122
Commercial Suicide Avatar answered Jan 14 '23 05:01

Commercial Suicide


Using the nth-child(xN+y) syntax...

.container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 25px;
}

.box {
  padding: 1em;
  border: 1px solid grey;
}

.container :nth-child(4n+2) {
  background: red;
}

.container :nth-child(4n+3) {
  background: blue;
}
<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
like image 29
Paulie_D Avatar answered Jan 14 '23 06:01

Paulie_D