With CSS alone this unfortunately isn't possible. The documentation for the :first-of-type
pseudo-class states:
The :first-of-type
pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element.
This means that :first-of-type
is applied to the first element of its type relative to its parent and not the document's root (or the body
element, in this case).
JavaScript solutions
:first-of-type
We can achieve this by introducing some JavaScript. All we need for this is JavaScript's querySelector()
method, which pulls the first matching element from the selector specified.
In this example I've altered your :first-of-type
pseudo-class to instead be a class of "first-of-type", then used JavaScript to add this class to the element returned when using querySelector('p')
:
document.querySelector('p').className += ' first-of-type';
p {
background:red;
}
p.first-of-type {
background: pink;
}
<body>
<section>
<p>111</p>
<p>222</p>
<p>333</p>
</section>
<p>444</p>
<p>555</p>
</body>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…