In the last lesson, the menu’s links started reacting to the mouse and the keyboard. Every selector so far has asked what an element is, what it carries, where it sits, or what’s happening to it. The plots page raises a different question. None of its table’s twenty-four rows carries a class or an ID. To a selector, they look exactly alike, and only the text tells plot 12 apart from the others.
In this lesson, you’ll select elements by their place among their siblings, such as the first, the last, the twelfth, or every other one. You’ll predict what a selector matches before you check it, and you’ll add a small decoration to the events pages that isn’t in the HTML at all. Start with the plots table.
Pick Rows by Their Position
On the plots page, you need to reach rows that the markup doesn’t name. Rosa would like the free plot to stand out one day, and long tables are easier to read with every other row shaded. CSS can’t match the word Free in a cell, because selectors look at elements and their attributes, never at their text.
You could add a class to every row you mean, but shading every other row would take twelve class attributes, and you’d have to move them all whenever a plot is added. Selecting a row by its position needs no extra markup.
Open plots.html, the page you built in HTML, in the live preview. It doesn’t load a stylesheet yet, so it’s black text on white. Here’s the start of its table body, with every row built the same way:
<tbody>
<tr><th scope="row">1</th>
<td>3 × 4 m</td><td>Ana</td></tr>
<tr><th scope="row">2</th>
<td>3 × 4 m</td><td>Jamal</td></tr>
<tr><th scope="row">3</th>
<td>3 × 4 m</td><td>Mei</td></tr>
You met pseudo-classes such as :hover in the last lesson as conditions on an element’s state. A structural pseudo-class is a condition on the element’s position among its siblings. :first-child matches an element that’s the first child of its parent, and :last-child one that’s the last.
Test them as you tested combinators. Open DevTools and click in the Elements panel. Then press Ctrl+F, or Cmd+F on macOS, and type tbody tr:first-child. The count reads 1 of 1. Hover over the highlighted <tr> in the tree, and the page highlights plot 1’s row. tbody tr:last-child finds plot 24.
Now leave out tbody and search for tr:first-child. The count reads 1 of 2, because the header row in <thead> is the first child of its own parent too. Position always counts within one parent, so tbody in front limits the selector to the plot rows.