Vinod kumar G
Vinod kumar G

Reputation: 655

How css is applied to a class as well as ID?

I have a table inside a div and CSS is provided to the tr with id="test" is not getting updated, when css for td is removed it is working. How the element is selected in css and why style is not applied to the tr?

#divID .w3-table #test {
  background-color: blue
}

#divID .w3-table td {
  background-color: yellow
}
<div id="divID">
  <table class="w3-table">
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Points</th>
    </tr>
    <tr id="test">
      <td>Jill</td>
      <td>Smith</td>
      <td>50</td>
    </tr>
    <tr>

  </table>
</div>

Upvotes: 1

Views: 47

Answers (2)

Ehsan
Ehsan

Reputation: 12959

Method A)

td always overlay tr. [#divID .w3-table td always overlay #divID .w3-table #test].

Note : #test is Id for tr.

For fix: you must insert td selector after id like this:

#divID .w3-table #test td {
  background-color: blue;
}

#divID .w3-table #test td {
  background-color: blue;
}

#divID .w3-table td {
  background-color: yellow;
}
<div id="divID">
  <table class="w3-table">
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Points</th>
    </tr>
    <tr id="test">
      <td>Jill</td>
      <td>Smith</td>
      <td>50</td>
    </tr>
    <tr>

  </table>
</div>

Method B)

You can use :not selector like this :

#divID .w3-table tr:not('#test') td {
  background-color: yellow;
}

#divID .w3-table tr:not('#test') td {
  background-color: yellow;
}

#divID .w3-table #test {
  background-color: blue;
}
<div id="divID">
  <table class="w3-table">
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Points</th>
    </tr>
    <tbody>    
    <tr id="test">
      <td>Jill</td>
      <td>Smith</td>
      <td>50</td>
    </tr>
  </table>
</div>

Upvotes: 0

Mathijs Segers
Mathijs Segers

Reputation: 6238

Because you're applying the css to the TR not the TD, so the TD has a background colour as well and the TR's is no longer visible. I suggest doing somethingg as follows:

divID .w3-table td{background-color:yellow}
divID .w3-table #test td{background-color:blue}

In this case we add the #test (which targets the id of the tr) and then nest the td afterwards, this should ensure your css works as expected since your implementation targets the tr#test and the td is inside that #test still.

It is also better to but the #test later, so it also overrides by being last otherwise in theory the yellow colour could still be applied since it is defined later (override).

Upvotes: 1

Related Questions