sylar32
sylar32

Reputation: 177

Targeting the next several siblings with CSS

I would need to find element by data attribute, apply some CSS to it, but also apply it to another several siblings next to it.

I have tried something like this, but it will apply only for the element with data attribute.

.fc-widget-header[data-date='2020-07-20T00:00:00']:nth-child(n+1):nth-child(-n+5) { color: #f00; }

I have also tried this, but it will apply css only for the first sibling of my element with data-attr.

.fc-widget-header[data-date='2020-07-20T00:00:00'] + .fc-widget-header:nth-child(n+1):nth-child(-n+5) { color: #f00; }

I need to apply to elements like this, for example for the first X elements (the number of elements is variable).

<th class="fc-widget-header" data-date="2020-07-20T00:00:00" colspan="2">
  <div class="fc-cell-content"><span class="fc-cell-text">po 20.</span></div>
</th>
<th class="fc-widget-header" data-date="2020-07-21T00:00:00" colspan="2">
  <div class="fc-cell-content"><span class="fc-cell-text">út 21.</span></div>
</th>
<th class="fc-widget-header" data-date="2020-07-22T00:00:00" colspan="2">
  <div class="fc-cell-content"><span class="fc-cell-text">st 22.</span></div>
</th>
<th class="fc-widget-header" data-date="2020-07-23T00:00:00" colspan="2">
  <div class="fc-cell-content"><span class="fc-cell-text">čt 23.</span></div>
</th>

Upvotes: 1

Views: 1185

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371133

Looks like you are looking for the general sibling combinator (~).

.fc-widget-header[data-date='2020-07-20T00:00:00'] ~ th {
  color: #f00;
}
<table>
  <th class="fc-widget-header" data-date="2020-07-20T00:00:00" colspan="2">
    <div class="fc-cell-content"><span class="fc-cell-text">po 20.</span></div>
  </th>
  <th class="fc-widget-header" data-date="2020-07-21T00:00:00" colspan="2">
    <div class="fc-cell-content"><span class="fc-cell-text">út 21.</span></div>
  </th>
  <th class="fc-widget-header" data-date="2020-07-22T00:00:00" colspan="2">
    <div class="fc-cell-content"><span class="fc-cell-text">st 22.</span></div>
  </th>
  <th class="fc-widget-header" data-date="2020-07-23T00:00:00" colspan="2">
    <div class="fc-cell-content"><span class="fc-cell-text">čt 23.</span></div>
  </th>
</table>

Essentially, the general sibling combinator (~) targets all subsequent siblings.

Note the distinction with the adjacent sibling combinator (+), which targets only the next sibling.

Upvotes: 2

Related Questions