There are two main points to consider:
If you do not include a tbody
element in your table, the browser will add one automatically (in most cases). So, when selecting elements using the child combinator (>
), remember to include tbody
in your selector like this:
#my-table > tbody > tr > td
. It is recommended to always include tbody
explicitly in your HTML to avoid any confusion.
The color of a table inside a td
element inherits its parent td
's color. This means that even though your selector targets the correct elements, their descendants inherit the color properties.
To work around this inheritance behavior, you can explicitly define colors for #my-table td
elements and then apply a special color only to
#my-table > tbody > tr > td
elements.
Here is an example to illustrate the concept:
#my-table td {
color: black;
}
#my-table > tbody > tr > td {
color: #ff0000;
}
<table id="my-table">
<tbody>
<tr>
<td>
I want to apply my style to this
</td>
<td>
<table>
<tr>
<td>
But not to this
</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
If you do not have control over the inner table, but have control over the outer table, you can label the cells you wish to style with a specific class and then target only those cells with the rule:
Example (note the tbody
in the HTML and also in the selector):
\
#my-table > tbody > tr > td.first {
color: #ff0000;
}
<table id="my-table">
<tbody>
<tr>
<td class="first">
I want to apply my style to this
</td>
<td>
<table>
<tr>
<td>
But not to this
</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>