CSS Pseudo-classes: Styling Elements Based on Their Index
CSS selector: pseudo-class selection based on the position of elements in the document subtree
Core points
- CSS provides a selector called a sub-index pseudo-class to match elements based on their position in the document subtree. These include
:first-child
,:last-child
,:only-child
,:nth-child()
,:nth-last-child()
and . -
:nth-child()
:nth-last-child()
andodd
pseudo-classes are functional and can accept parameters in the form ofeven
keyword,An B
keyword, integer, or , where A is the step interval and B is the bias Shift, n is a positive integer. -
:only-child
<code>:empty Pseudo-class matches the element if the element is the only child of another element. The pseudo-class can select elements without child elements, not even spaces. -
:first-of-type
CSS provides typed sub-index pseudo-classes that match elements based on index values, but are limited to elements of a specific type. These include:last-of-type
,:only-of-type
,:nth-of-type()
,:nth-last-of-type()
, and
- CSS also provides selectors for matching elements based on their position in the document subtree. These are called sub-index pseudo-classes because they depend on the position or order of the element, not its type, attribute, or ID. There are five in total:
-
:first-child
-
:last-child
-
:only-child
-
:nth-child()
-
:nth-last-child()
:first-child
:last-child
and :first-child
:last-child
As you guessed from the name, the :first-child
and :last-child
pseudo-classes can be used to select elements that are the first or last child elements of a node (element). Like other pseudo-classes,
have the least side effects when defined by simple selectors.
<meta charset="utf-8"> <title>:first-child and :last-child</title> <body> <style> body { font: 16px/1.5 sans-serif; } :first-child { color: #e91e63; } :last-child { color: #4caf50; } </style> <h2 id="List-of-fruits">List of fruits</h2> <ul> <li>Apples</li> <li>Bananas</li> <li>Blueberries</li> <li>Oranges</li> <li>Strawberries</li> </ul> </body>
You can see what it looks like in the picture below.
:first-child
h2
Because li
is not limited, the h2
element and the first body
element are pink. After all, li
is the first child element of ul
, and li
is the first child element of the :last-child
element. But why are the remaining ul
elements green? That's because body
is not limited either, *:first-child
is the last child element of *:last-child
. We actually typed
If we qualify :first-child
and :last-child
by adding a simple selector, then this makes all more sense. Let's limit the selection to list items. Change :first-child
to li:first-child
, and :last-child
to li:last-child
. The following figure shows the results.
:nth-child()
and :nth-last-child()
It is nice to be able to select the first and last child elements of the document. But what if we want to select odd or even elements? Maybe we want to select the sixth element in the document subtree, or apply the style to every three elements. This is where the :nth-child()
and :nth-last-child()
pseudo-classes come into play.
Like :not()
, :nth-child()
and :nth-last-child()
are also functional pseudo-classes. They accept a parameter which should be:
odd
Keywordseven
Keywords- An integer, such as 2 or 8, or Parameters in the form
An B
, where A is the step interval, B is the offset, and n is the variable representing a positive integer.
The last item has some complexity. We'll discuss it later.
What is the difference between:nth-child()
and :nth-last-child()
? Starting point: :nth-child()
Count forward, :nth-last-child()
Count backward. The CSS index uses count numbers, starting with 1 instead of 0.
:nth-child()
and :nth-last-child()
can be used in alternating modes. Creating zebra pattern table row colors is the perfect use case. The following CSS provides a light blue-gray background for even-numbered table rows, and the result can be seen in the following figure:
<meta charset="utf-8"> <title>:first-child and :last-child</title> <body> <style> body { font: 16px/1.5 sans-serif; } :first-child { color: #e91e63; } :last-child { color: #4caf50; } </style> <h2 id="List-of-fruits">List of fruits</h2> <ul> <li>Apples</li> <li>Bananas</li> <li>Blueberries</li> <li>Oranges</li> <li>Strawberries</li> </ul> </body>
Switching :nth-child
to :nth-last-child
will reverse this band because the count starts at the bottom, as shown below.
How to try some complex examples of more complex parameters? We will start with the document shown below, which contains 20 items.
Using :nth-child()
and :nth-last-child()
, we can select individual child elements at a specific location. We can select all the child elements of after a specific position, or we can select elements by multiples, with an offset. Let's change the background color of the sixth project:
<meta charset="utf-8"> <title>:first-child and :last-child</title> <body> <style> body { font: 16px/1.5 sans-serif; } :first-child { color: #e91e63; } :last-child { color: #4caf50; } </style> <h2 id="List-of-fruits">List of fruits</h2> <ul> <li>Apples</li> <li>Bananas</li> <li>Blueberries</li> <li>Oranges</li> <li>Strawberries</li> </ul> </body>
grammar comes into play: An B
tr:nth-child(even) { background: rgba(96, 125, 139, 0.1); }
and :nth-child()
to select all elements after a point. Let's try to select all elements except the first seven elements: :nth-last-child()
.item:nth-child(6) { background: #e91e63; }
Negative offset and range values are also valid. Using
will reverse our selection and match the first eight elements. :nth-child(-n 8)
.item:nth-child(3n) { background: #e91e63; }
:only-child
If the element is a s unique child of another element, then the pseudo-class matches that element. Below are two unordered lists. The first one has a project, while the second one contains three: :only-child
.item:nth-child(n+8) { background: #e91e63; }
Apple will be selected because it is the only child element of our first list. However, any items in the second list do not match because there are three sibling elements. You can see what it looks like in the picture below. li:only-child{color: #9c27b0;}
<code>:empty
You can also use the <code>:empty pseudo-class to select elements without child elements. When we say <code>:empty, we mean empty. To make the element match the <code>:empty pseudo-class, it cannot contain anything else—even spaces. In other words, <code><p></p>
<p> </p>
will match, but <code>:empty
:not()
will not match. Sometimes the WYSIWYG editor inserts an empty p element into your content. You can use p:not(:empty)
in combination with
.
Select specific types of elements by their indexp:nth-last-child(2)
selects each p element that is the penultimate element of its parent element.
In this section, we will discuss typed sub-index pseudo-classes. These pseudo-classes also match elements based on their index values; however, matches are limited to elements of a specific type. For example, select the fifth p element, or the h2 element with an even index.
- There are five such pseudo-classes with the same name as their non-typed counterpart:
-
:first-of-type
:last-of-type
:only-of-type
:nth-of-type()
:nth-last-of-type()
p:nth-child(5)
p:nth-of-type(5)
The difference between these pseudo-classes and sub-index pseudo-classes is subtle. Where
matches all p elements, and then finds the fifth p element among these elements.
Let's start with a slightly different document. It still has 20 items, but some of them are p elements and some are div elements. The p element has rounded corners as shown below.
:first-of-type
:last-of-type
Use :only-type
,
and :first-of-type
<meta charset="utf-8"> <title>:first-child and :last-child</title> <body> <style> body { font: 16px/1.5 sans-serif; } :first-child { color: #e91e63; } :last-child { color: #4caf50; } </style> <h2 id="List-of-fruits">List of fruits</h2> <ul> <li>Apples</li> <li>Bananas</li> <li>Blueberries</li> <li>Oranges</li> <li>Strawberries</li> </ul> </body>
This will match each p element that is the first p element of its parent element, as shown below.
:last-of-type
The pseudo-class works similarly, which matches the last such element of its parent element, as shown below. However, if an element is a :only-of-type
s unique
Let's look at another example using :first-of-type
, but this time using a pseudo-element. Do you still remember the ::first-letter
pseudo-element mentioned earlier in this chapter? Well, as you can see, it creates an initial capital letter for each element that applies it. Let's go a step further and limit this initial capital letter to the first paragraph:
<meta charset="utf-8"> <title>:first-child and :last-child</title> <body> <style> body { font: 16px/1.5 sans-serif; } :first-child { color: #e91e63; } :last-child { color: #4caf50; } </style> <h2 id="List-of-fruits">List of fruits</h2> <ul> <li>Apples</li> <li>Bananas</li> <li>Blueberries</li> <li>Oranges</li> <li>Strawberries</li> </ul> </body>
As shown in the following image, now our paragraph will have an initial capital letter, even if it is preceded by the title.
Use :nth-of-type
and :nth-last-of-type
:nth-of-type()
and :nth-last-of-type()
are also functional pseudo-classes. They accept the same parameters as :nth-child()
and :nth-last-child()
. But like :first-of-type
and :last-of-type
, the index resolves to the same type of elements. For example, to select the first p element and each subsequent p element, we can use the odd
keyword with :nth-of-type()
:
tr:nth-child(even) { background: rgba(96, 125, 139, 0.1); }
As you can see from the image below, this will only match the odd numbered p element, not the odd numbered child element.
Similarly, use :nth-last-of-type(even)
to select an even numbered p element, but the count starts with the last p element in the document - in this case Item 18 (see below).
If this still looks blurry, use Paul Maloney’s Nth-Test tool, or check out the examples on Nth Master. Both projects are excellent ways to learn more about these pseudo-classes.
[5] This An B
syntax is described in CSS syntax module level 3.
FAQs about CSS pseudo-classes and index-based element styles
What is a CSS pseudo-class?
CSS pseudo-class is a keyword added to the selector and is used to specify the special state of the selected element. For example, :hover
can be used to change the color of a button when the user's pointer hovers over it. A pseudo-class, together with class and ID, is a way to apply styles to elements without changing HTML tags.
:nth-child
How do pseudo-classes work?
:nth-child
Pseudo-class matches elements based on the position of elements in a group of simultaneous elements. It uses a function-like syntax :nth-child(an b)
where "a" and "b" are integer values. "n" is a counter starting at 0 and increments by 1 for each element. "an b" means the element to be selected, starting with the first element (b=1).
:nth-child
and :nth-of-type
?
:nth-child
Matches elements based on the position of an element in all its sibling elements, while :nth-of-type
only considers positions in sibling elements of the same type. For example, if it is a <code>p:nth-child(2)
element, a second child element is selected, and <code><p></p> will select the second <code>p:nth-of-type(2)
element, and Regardless of its position in other sibling elements. <code><p></p>
You can use the
pseudo-class with a class selector. For example, :nth-child
will select the first element with class "myClass". Remember that this works only if the element is the first child of its parent element. .myClass:nth-child(1)
? :nth-child
No, Negative values are not allowed. The minimum value you can use is 0, which does not select any elements. :nth-child
You can use the "even" and "odd" keywords with
to select each even or odd element. For example, :nth-child
will select each second element starting from the first element. :nth-child(even)
with other pseudo-classes? :nth-child
Yes, you can use in combination with other pseudo-classes. For example, :nth-child
will apply the style when the user's pointer is hovered over the second child element. :nth-child(2):hover
Is there a performance difference between
and :nth-child
? :nth-of-type
In most cases, the performance differences are negligible. However, when dealing with large numbers of elements, is probably slightly faster because it only considers sibling elements of the same type. :nth-of-type
with pseudo-elements? :nth-child
No, pseudo-elements cannot be used with because they are not considered part of the document tree. :nth-child
Are there any browser compatibility issues? :nth-child
All modern browsers are well supported . However, it is not supported by Internet Explorer 8 or earlier. For these browsers, you may need to use JavaScript or jQuery to achieve similar effects. :nth-child
The above is the detailed content of CSS Pseudo-classes: Styling Elements Based on Their Index. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

CSS Grid is a collection of properties designed to make layout easier than it’s ever been. Like anything, there's a bit of a learning curve, but Grid is

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference
