Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does :nth-child not work as expected with a table having a caption?

Tags:

html

css

tr:nth-child does not select the expected row when the table it applies to has a caption.

When a section has a h2 and several p as children, p:nth-child(2) selects the first p after the h2, which is what is expected. However, when using tr:nth-child(2) on a table with several rows and a caption that naturally follows the opening table tag, the selector target the second tr, as if the caption did not exist.

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

p:nth-child(2) {
  background-color: red;
}
<table>
  <caption>This caption is the table's first child</caption>
  <tr>
    <th>First row</th>
    <td>1.2</td>
    <td>1.3</td>
    <td>1.4</td>
  </tr>
  <tr>
    <th>Second row</th>
    <td>2.2</td>
    <td>2.3</td>
    <td>2.4</td>
  </tr>
  <tr>
    <th>Third row</th>
    <td>3.2</td>
    <td>3.3</td>
    <td>3.4</td>
  </tr>
</table>

<section>
  <h1>Title (h1)</h1>
  <p>First paragraph</p>
  <p>Second paragraph</p>
  <p>Third paragraph</p>
</section>

I expect the tr:nth-child(2) to select the first row since the 1st child of the table is the caption.

like image 716
user3589345 Avatar asked May 20 '19 11:05

user3589345


People also ask

Does nth child work with class?

The :nth-child() CSS pseudo-class matches elements based on their position among a group of siblings.

Which nth child () selector will target only the last list item?

The :last-child selector allows you to target the last element directly inside its containing element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

What is the difference between the nth child () and Nth of type () selector?

As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .

How do you target the nth child in SCSS?

You can pass in a positive number as an argument to :nth-child() , which will select the one element whose index inside its parent matches the argument of :nth-child() . For example, li:nth-child(3) will select the list item with an index value 3; that is, it will select the third list item.


1 Answers

tr elements cannot be child elements of a table

They must be child elements of a tbody, thead, or tfoot element.

tbody elements have optional start and end tags and are inserted implicitly if the author does not insert them explicitly.

The first tr is the first child of the tbody element, and is not a child of the table element at all.

See this in the DOM inspector

like image 94
Quentin Avatar answered Oct 20 '22 08:10

Quentin