csscss-selectors

Selector to match all similar elements with the same class after an element?


I am trying to get a CSS selector to match the elements with the .disabled class name, but only after the element with .today class name. It should match Day 11, Day 12 & Day 13 elements in below example.

Here is my HTML:

<div class="month">
  <div class="week">
    <div class="day disabled">Day 1</div>
    <div class="day disabled">Day 2</div>
    <div class="day disabled">Day 3</div>
    <div class="day today">Day 4</div>
    <div class="day">Day 5</div>
    <div class="day">Day 6</div>
    <div class="day">Day 7</div>
  </div>
</div>
<div class="month">
  <div class="week">
    <div class="day">Day 8</div>
    <div class="day">Day 9</div>
    <div class="day">Day 10</div>
    <div class="day disabled">Day 11</div>
    <div class="day disabled">Day 12</div>
    <div class="day disabled">Day 13</div>
    <div class="day">Day 14</div>
  </div>
</div>

I have tried this selector, but it will only work on elements in the same level as .today class:

.today ~ .disabled: {
  background: red
}

Any idea if this can be done?


Solution

  • You could using some version of :has and iterating up the DOM but it would be incredibly brittle.

    .week {
      outline: 1px solid grey;
      margin-bottom: .25em;
    }
    
    .month .week .today {
      background: lightgreen;
    }
    
    .month:has(.today)~.month .week .disabled {
      background: lightblue;
    }
    <div class="month">
      <div class="week">
        <div class="day disabled">Day 1</div>
        <div class="day disabled">Day 2</div>
        <div class="day disabled">Day 3</div>
        <div class="day today">Day 4</div>
        <div class="day">Day 5</div>
        <div class="day">Day 6</div>
        <div class="day">Day 7</div>
      </div>
    </div>
    <div class="month">
      <div class="week">
        <div class="day">Day 8</div>
        <div class="day">Day 9</div>
        <div class="day">Day 10</div>
        <div class="day disabled">Day 11</div>
        <div class="day disabled">Day 12</div>
        <div class="day disabled">Day 13</div>
        <div class="day">Day 14</div>
      </div>
    </div>