Search code examples
htmlcss

How to override CSS nth-child selector property from the HTML


Overriding background-color of the .gantt-row class below is easily done by adding a style attribute to the DIV:

<div style="background-color: blue" class="gantt-row">

Is it also possible to override the background-color of the gantt-row:nth-child selectors from within the markup? Or is it necessary to use jQuery for this?

.gantt-row {
    display: grid;
    grid-template-columns: 150px 1fr;
    background-color: #fff;
}

.gantt-row:nth-child(even) {
    background-color: #F6F6F6;
}

.gantt-row:nth-child(even) .gantt-row-name {
    background-color: #F6F6F6;
}

Solution

  • You can't directly affect the style of the nth-child element like that, but you can set CSS variables which can be picked up when styling a property.

    In this snippet a parent container can be styled inline with a --bg variable setting and this can be picked up by the settings for the nth-child(even).

    .gantt-row {
      display: grid;
      grid-template-columns: 150px 1fr;
      background-color: #fff;
    }
    
    .gantt-row:nth-child(even) {
      background-color: var(--bg);
    }
    
    .gantt-row:nth-child(even) .gantt-row-name {
      background-color: var(--bg);
    }
    <div style="--bg: blue;">
      <div class="gantt-row">odd</div>
      <div class="gantt-row">even</div>
    </div>

    Note, it doesn't have to be a direct parent, any ancestor will do.