Home >Web Front-end >CSS Tutorial >CSS Pseudo-classes: Styling Elements Based on Their Index

CSS Pseudo-classes: Styling Elements Based on Their Index

Lisa Kudrow
Lisa KudrowOriginal
2025-02-19 11:26:09173browse

CSS selector: pseudo-class selection based on the position of elements in the document subtree

CSS Pseudo-classes: Styling Elements Based on Their Index

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() and odd pseudo-classes are functional and can accept parameters in the form of even 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-typeCSS 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,

and

have the least side effects when defined by simple selectors.

<code class="language-html"><meta charset="utf-8">
<title>:first-child and :last-child</title>

  <style>
    body {
      font: 16px/1.5 sans-serif;
    }
    :first-child {
      color: #e91e63;
    }
    :last-child {
      color: #4caf50;
    }
  </style>
  <h2>List of fruits</h2>
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Blueberries</li>
    <li>Oranges</li>
    <li>Strawberries</li>
  </ul>
</code>
Let's take a look at the HTML and CSS below:

You can see what it looks like in the picture below. CSS Pseudo-classes: Styling Elements Based on Their Index

:first-child h2Because 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

and .

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.

CSS Pseudo-classes: Styling Elements Based on Their Index

: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 Keywords
  • even 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.

Both

: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:

<code class="language-html"><meta charset="utf-8">
<title>:first-child and :last-child</title>

  <style>
    body {
      font: 16px/1.5 sans-serif;
    }
    :first-child {
      color: #e91e63;
    }
    :last-child {
      color: #4caf50;
    }
  </style>
  <h2>List of fruits</h2>
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Blueberries</li>
    <li>Oranges</li>
    <li>Strawberries</li>
  </ul>
</code>

CSS Pseudo-classes: Styling Elements Based on Their Index

Switching :nth-child to :nth-last-child will reverse this band because the count starts at the bottom, as shown below.

CSS Pseudo-classes: Styling Elements Based on Their Index

How to try some complex examples of more complex parameters? We will start with the document shown below, which contains 20 items.

CSS Pseudo-classes: Styling Elements Based on Their Index

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:

<code class="language-html"><meta charset="utf-8">
<title>:first-child and :last-child</title>

  <style>
    body {
      font: 16px/1.5 sans-serif;
    }
    :first-child {
      color: #e91e63;
    }
    :last-child {
      color: #4caf50;
    }
  </style>
  <h2>List of fruits</h2>
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Blueberries</li>
    <li>Oranges</li>
    <li>Strawberries</li>
  </ul>
</code>
This gives us the following results.

CSS Pseudo-classes: Styling Elements Based on Their Index

But what if we want to select every three elements? This is where

grammar comes into play: An B

<code class="language-css">tr:nth-child(even) {
  background: rgba(96, 125, 139, 0.1);
}</code>
Similarly, A is the step length interval. It's almost like a multiplier of n, starting with 1. Therefore, if A = 3, then 3n will match elements such as 3, 6, 9. This is exactly what happens, as you can see below.

CSS Pseudo-classes: Styling Elements Based on Their Index

There is a place where things get more interesting. We can use

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()

<code class="language-css">.item:nth-child(6) {
  background: #e91e63;
}</code>
There is no step size value here. Therefore, n 8 matches each element n starting from the eighth element, as shown below.

CSS Pseudo-classes: Styling Elements Based on Their Index

Note: Negative offset

Negative offset and range values ​​are also valid. Using

will reverse our selection and match the first eight elements. :nth-child(-n 8)

We can also select every three elements using offset and step size values, starting from the fifth one:

<code class="language-css">.item:nth-child(3n) {
  background: #e91e63;
}</code>
You can see the results of this selector in the following image.

CSS Pseudo-classes: Styling Elements Based on Their Index

: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

<code class="language-css">.item:nth-child(n+8) {
  background: #e91e63;
}</code>
Using

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;}

CSS Pseudo-classes: Styling Elements Based on Their Index

<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

pseudo-classes to avoid applying styles to these elements; for example

.

Select specific types of elements by their indexp:nth-last-child(2)

The pseudo-class discussed in the previous section matches the element if it occupies a given position in the document subtree. For example,

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 the fifth item only if it is a p element,

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. CSS Pseudo-classes: Styling Elements Based on Their Index

:first-of-type :last-of-typeUse :only-type,

and

:first-of-type

Using
<code class="language-html"><meta charset="utf-8">
<title>:first-child and :last-child</title>

  <style>
    body {
      font: 16px/1.5 sans-serif;
    }
    :first-child {
      color: #e91e63;
    }
    :last-child {
      color: #4caf50;
    }
  </style>
  <h2>List of fruits</h2>
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Blueberries</li>
    <li>Oranges</li>
    <li>Strawberries</li>
  </ul>
</code>
, we can select the first element that matches the selector. How do we provide a lime green background for the first p element:

This will match each p element that is the first p element of its parent element, as shown below. CSS Pseudo-classes: Styling Elements Based on Their Index

: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-types unique

of its parent element, then will match that element as shown below.

CSS Pseudo-classes: Styling Elements Based on Their Index CSS Pseudo-classes: Styling Elements Based on Their Index

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:

<code class="language-html"><meta charset="utf-8">
<title>:first-child and :last-child</title>

  <style>
    body {
      font: 16px/1.5 sans-serif;
    }
    :first-child {
      color: #e91e63;
    }
    :last-child {
      color: #4caf50;
    }
  </style>
  <h2>List of fruits</h2>
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Blueberries</li>
    <li>Oranges</li>
    <li>Strawberries</li>
  </ul>
</code>

As shown in the following image, now our paragraph will have an initial capital letter, even if it is preceded by the title.

CSS Pseudo-classes: Styling Elements Based on Their Index

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():

<code class="language-css">tr:nth-child(even) {
  background: rgba(96, 125, 139, 0.1);
}</code>

As you can see from the image below, this will only match the odd numbered p element, not the odd numbered child element.

CSS Pseudo-classes: Styling Elements Based on Their Index

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).

CSS Pseudo-classes: Styling Elements Based on Their Index

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).

What is the difference between

: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>

How to select the first, second or third element using the given class name?

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)

Can I use negative values ​​in

? :nth-child

No,

Negative values ​​are not allowed. The minimum value you can use is 0, which does not select any elements. :nth-child

How to select each even or odd element?

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)

Can I use

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

Can I use

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

All pictures remain in their original format and location. <p></p>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn