HTML and CSS Reference
In-Depth Information
Selecting first and last of a type
In a manner similar to selecting the first and last children of an element, you can select
the first or last of a type of element within an element. This permits things like selecting
the first table inside a given element, regardless of whatever other elements come
before it.
table:first-of-type {border-top: 2px solid gray;}
Note that this does not apply to the entire document; that is, the rule shown will not
select the first table in the document and skip all the others. It will instead select the
first table element within each element that contains one, and skip any sibling table
elements that come after the first. Thus, given the document structure shown in Fig-
ure 1-29 , the circled nodes are the ones that are selected.
Figure 1-29. Selecting first-of-type tables
Within the context of tables, a useful way to select the first data cell within a row
regardless of whether a header cell comes before it in the row is as follows:
td:first-of-type {border-left: 1px solid red;}
That would select the first data cell in each of the following table rows:
<tr><th scope="row">Count</th><td>7</td><td>6</td><td>11</td></tr>
Compare that to the effects of td:first-child , which would select the first td element
second row shown, but not in the first row.
The flip side is :last-of-type , which selects the last instance of a given type from
amongst its sibling elements. In a way, it's just like :first-of-type except you start
with the last element in a group of siblings and walk backwards toward the first element
until you reach an instance of the type. Given the document structure shown in Fig-
ure 1-30 , the circled nodes are the ones selected by table:last-of-type .
As was noted with :only-of-type , remember that you are selecting elements of a type
from among their sibling elements; thus, every set of siblings is considered separately.
In other words, you are not selecting the first (or last) of all the elements of a type within
the entire document as a single group. Each set of elements that share a parent is its
own group, and you can select the first (or last) of a type within each group.
Search WWH ::

Custom Search