Css selector

how to select the first element of the same class?

<!DOCTYPE html>
<html>
<head>
<style> 
.test:nth-of-type(1)
{
background:-sharpff0000;
}
</style>
</head>
<body>

<h1></h1>

<p class="test">

<p class="test">

.test: what about nth-of-type (1) and nth-of-child (1)?
how do I want the first p.test to turn red

Mar.25,2022

W3C there are several categories of definitions of selectors, including: type, class, id, etc.

the type of the H1 tag is H1, and the type of the p tag is p

description of nth-of-type in the W3C document:

an element's index among elements of the same type (tag name) in their sibling list.

so : nth-of-type (1) is actually used to match the first element in the set of all sibling elements of the same type.

< hr >

it was said before that the subject used the error, but it is actually

that there is no problem with the code.

but .test: nth-of-type (1)

the correct matching logic should be:

*:nth-of-type(1)  class`.test`

wrong matching logic, the cause of the problem

`.test`

nth-of-child is the same logic, and if you don't know much about it, you can take a look at the 45th example in my reference below.

refer to
W3C selector4 draft
because there are not enough cases of standard documents in selector3, so I read the draft of 4.

Menu