0

I have the following HTML and am trying to make the header row of the table bold.

<!DOCTYPE html>
<html>

<head>
  <style>
    table>tr>th {
      font-weight: bold;
    }
  </style>
</head>

<body>
  <table>
    <tr>
      <th>Amount</th>
      <th>Name</th>
    </tr>
    <tr>
      <td>5</td>
      <td>orange</td>
    </tr>
  </table>
</body>

</html>

It does not work with this rule, but if I use table tr > th, it works. Why is that? From my understanding it should work because the <tr> is a direkt child of the <table> and the <th> is a direct child of the <tr>. What did I get wrong here?

Kameron
  • 10,240
  • 4
  • 13
  • 26
  • Because your browser injects an `tbody` between `table` and `tr`. So you'll need `table > tbody > tr > th`. But it's better to include that `tbody` in the HTML. – 0stone0 Feb 27 '23 at 15:51
  • Note that your example doesn't demonstrate the problem because the **default** font weight for a th element is bold. – Quentin Feb 27 '23 at 15:51

1 Answers1

2

Note that your example doesn't demonstrate the problem because the default font weight for a th element is bold.


However, the problem does exist:

A tr element cannot be a child element of a table.

A tr element can be a child element of thead, tbody or tfoot element.

The start and end tags of a tbody element may be omitted.

Thus, if you write:

 <table><tr>...</tr></table>

The tbody element is inferred and the DOM is:

 <table><tbody><tr>...</tr></tbody></table>

The tr element is a grandchild of the table element, not a child.

table>tr>th {
  color: blue;
}

table>tbody>tr>th {
  color: pink;
}
<table>
  <tr>
    <th>Amount</th>
    <th>Name</th>
  </tr>
  <tr>
    <td>5</td>
    <td>orange</td>
  </tr>
</table>
0stone0
  • 34,288
  • 4
  • 39
  • 64
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I'd appreciate it if you rephrased the "cannot be a child element of `table`" part, as at first glance it is confusing. – Zachiah Feb 27 '23 at 15:55
  • @Zachiah — It's a simple factual statement. I don't understand why you find it confusing. (So I can't rephrase it to make it less confusing to you.) – Quentin Feb 27 '23 at 16:02
  • Maybe say it as "cannot be a child element of `table` in the DOM", because in it's current state it is unclear if you are referring to the DOM or the psuedo-XML structure of the HTML document I guess. (Not sure if that made any sense but it did to me (: ) – Zachiah Feb 27 '23 at 16:09