nowox
nowox

Reputation: 29096

Apply CSS style to the first element of type when already using :nth-child

In the following example I would like to not apply any background color to the cell Not here....

In other words, I would like to apply my CSS .class tag:modifer only for the first child element of type tag.

.foo {
border-collapse: collapse;
}

.foo tr:nth-child(1) td:nth-child(1) {
background-color: green;
}

.foo tr:nth-child(2) td:nth-child(2) {
background-color: red;
}
<table class="foo">
  <tr><td>A</td><td>B</td></tr>
  <tr><td>C</td>
  <td>
     <table><tr><td>Not here...</td></tr></table>
  </td>
  </tr>
</div>

Upvotes: 1

Views: 707

Answers (2)

Temani Afif
Temani Afif

Reputation: 272909

You can override the style using another selector:

.foo {
  border-collapse: collapse;
}

.foo tr:nth-child(1) td:nth-child(1) {
  background-color: green;
}

.foo tr:nth-child(2) td:nth-child(2) {
  background-color: red;
}

.foo table td:not(#random_id_for_specificity){
  all:initial; /*to override everything*/
}
<table class="foo">
  <tr>
    <td>A</td>
    <td>B</td>
  </tr>
  <tr>
    <td>C</td>
    <td>
      <table>
        <tr>
          <td>Not here...</td>
        </tr>
      </table>
    </td>
  </tr>
</table>

Upvotes: 1

zer00ne
zer00ne

Reputation: 43880

  1. Use direct descendant combinator >
  2. Find an ancestor higher up the tree <div>
  3. Use nth-of-type
div > table > tbody > tr:first-of-type > td:first-of-type 

.foo {
  border-collapse: collapse;
}

div>table>tbody>tr:first-of-type>td:first-of-type {
  background-color: green;
}

.foo tr:nth-child(2) td:nth-child(2) {
  background-color: red;
}
<div>
  <table class="foo">
    <tr>
      <td>A</td>
      <td>B</td>
    </tr>
    <tr>
      <td>C</td>
      <td>
        <table>
          <tr>
            <td>Not here...</td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</div>

Upvotes: 1

Related Questions