hide nth child items after multiple of 7

34 Views Asked by At

So I have items set out from a cms and no control over their number.

I want to use css to hide all items over a multiple of 7, but only the last few.

I.e. if there are 10 items I need to hide the last 3, if there are 22 items I need to hide the last one... (the remainder after dividing by 7).

I've tried a combination of nth child and nth last child, but haven't got close!

2

There are 2 best solutions below

3
Temani Afif On

You need to cover a lot of cases. To be more precise, you have 6 different cases based on the position of the (7n + 1) item.

var box = document.querySelector(".box");
document.querySelector("button").addEventListener("click", (event) => {box.appendChild(document.createElement("div"))});
.box {
  display: grid;
  grid-template-columns: repeat(7,1fr);
  gap: 10px;
  margin: 5px;
  border: 1px solid;
}

.box div {
  height: 20px;
  background: red;
}

.box :nth-child(7n + 1):nth-last-child(1),
.box :nth-child(7n + 1):nth-last-child(2),
.box :nth-child(7n + 1):nth-last-child(2) ~ *,
.box :nth-child(7n + 1):nth-last-child(3),
.box :nth-child(7n + 1):nth-last-child(3) ~ *,
.box :nth-child(7n + 1):nth-last-child(4),
.box :nth-child(7n + 1):nth-last-child(4) ~ *,
.box :nth-child(7n + 1):nth-last-child(5),
.box :nth-child(7n + 1):nth-last-child(5) ~ *,
.box :nth-child(7n + 1):nth-last-child(6),
.box :nth-child(7n + 1):nth-last-child(6) ~ * {
  display: none;
}
<div class="box">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

<button>add item</button>

You can optimize like below:

var box = document.querySelector(".box");
document.querySelector("button").addEventListener("click", (event) => {box.appendChild(document.createElement("div"))});
.box {
  display: grid;
  grid-template-columns: repeat(7,1fr);
  gap: 10px;
  margin: 5px;
  border: 1px solid;
}

.box div {
  height: 20px;
  background: red;
}

.box :nth-child(7n + 1):nth-last-child(-n + 6),
.box :nth-child(7n + 1):nth-last-child(-n + 6) ~ * {
  display: none;
}
<div class="box">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

<button>add item</button>

0
Adam Strags On

Sussed - useful for anyone else...

li:nth-last-child(-n + 8) + li:nth-child(7n) ~ li{
  display: none;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul>