It’s fairly common to provide the first appearance of an element with a particular look: italicizing the first paragraph on a page, for example, or creating a first-line run-in effect. Traditionally, this has been achieved by applying an id
to the affected element. There are significant drawbacks to that approach: every time we create a new first paragraph, we must remember to apply the id
to create the effect. It is much easier to create a consistent rule that works in a particular context, rather than depending on developer intervention.
If we disavow use of id’s, classes and inline styles due to their inefficiency, then there are two solutions to customizing the appearance of the first instance of an element.
The first-child selector
The first-child
pseudo-selector matches the first element in a particular context. For example, to select the first instance of a paragraph in the body, we could use:
body p:first-child {
font-weight: 800;
}
It’s probably easiest to read this selector in reverse: “If the first element inside the body is a paragraph, make it extra-bold”.
However, this only works if the paragraph is not preceded by any other markup: if there is a heading before it, the paragraph is no longer the first child of the body, and will not be affected by the rule.
first-of-type and nth-of-type selector
Although less common, the best and most adaptable solution is to use a first-of-type
or nth-of-type
selector. Very simply, the CSS selectors do what they say: match the first or nth instance of an element in a particular context. Continuing our example above (the first paragraph inside a page) we could write:
p:first-of-type {
font-style: italic;
}
Alternatively:
p:nth-of-type(1) {
font-style: italic;
}
The number in parentheses at the end of the selector simply indicates which element is to be affected: 1 represents the first matching element, 2 the second, and so on. It’s also possible to place calculations in the parentheses.
Using first-of-type
or nth-of-type
above means that the paragraph could be preceded by any amount of markup or content, and still be affected by the style. You can, of course, make this more specific, and combine it with other pseudo-selectors:
article p:first-of-type:first-line {
font-feature-settings:"smcp";
}
With the addition of appropriate vendor prefixes for the font-feature-settings
property, the declaration above would select the first line of the first paragraph in any article and render it in true small caps.
Photograph by Janeen, used under a Creative Commons license
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.