no use for a name
no use for a name

Reputation: 658

Select N next siblings in relation to the selected element (with unique class attached) using CSS (LESS)

I have HTML code below. Let's say, I'm able to attach the selected-day class by clicking on each span. I'm trying to select the next 6 siblings, starting from the element with the class selected-day. Here's what I have came up with:

#calendar span.day.selected-day {
  background-color: red;
  ~ span:nth-child(n + 6):nth-child(-n + 15) {
    background-color: red;
  }
}
<div id="calendar">
	<span class="day">1</span>
	<span class="day">2</span>
	<span class="day">3</span>
	<span class="day">4</span>
	<span class="day">5</span>
	<span class="day selected-day">6</span>
	<span class="day">7</span>
	<span class="day">8</span>
	<span class="day">9</span>
	<span class="day">10</span>
	<span class="day">11</span>
	<span class="day">12</span>
	<span class="day">13</span>
	<span class="day">14</span>
	<span class="day">15</span>
	<span class="day">16</span>
</div>

While it correctly highlights selected days at the beginning:

enter image description here

Whenever I change the selection, it doesn't follow:

enter image description here

Is there any proper way to always select the next 6 sibling in relation to the element with the given class?

Upvotes: 1

Views: 66

Answers (1)

Insomnia88
Insomnia88

Reputation: 368

Well it doesn't look elegant but you can simply add multiple selectors. Since I don't use less I write the example in native css

#calendar span.day.selected-day + span,
#calendar span.day.selected-day + span + span,
#calendar span.day.selected-day + span + span + span,
#calendar span.day.selected-day + span + span + span + span,
#calendar span.day.selected-day + span + span + span + span + span,
#calendar span.day.selected-day + span + span + span + span + span + span {
    background-color: red;
}

Edit: I tried it in LESS

#calendar span.day.selected-day {
  background-color: red;
  + span,
  + span + span,
  + span + span + span,
  + span + span + span + span,
  + span + span + span + span + span,
  + span + span + span + span + span + span
  {
    background-color: red;
  }
}

Upvotes: 2

Related Questions