Home > Web Front-end > CSS Tutorial > How to Select the Last Child Element with a Specific Class in CSS?

How to Select the Last Child Element with a Specific Class in CSS?

DDD
Release: 2024-12-29 03:05:09
Original
902 people have browsed it

How to Select the Last Child Element with a Specific Class in CSS?

Selecting Last Child Element with a Specific Class in CSS

In CSS, targeting the last child element of a parent element with a specific class name can be achieved using attribute selectors. Consider the following HTML markup:

<ul>
    <li class="list">test1</li>
    <li class="list">test2</li>
    <li class="list">test3</li>
    <li>test4</li>
</ul>
Copy after login

To select the last child element with the class name "list," you can use the following CSS:

[class~='list']:last-of-type {
    background: #000;
}
Copy after login

Understanding the CSS Selector:

  • [class~='list'] matches any element that has the class name "list." The class name can be placed anywhere within the element's class attribute, whether it's the first, second, or last class.
  • :last-of-type selects the last child element that matches the preceding selector. This ensures that only the last child element with the class name "list" is targeted.

Advantages of Using Attribute Selectors:

Unlike CSS pseudo-classes like :nth-child(), attribute selectors offer the following advantages:

  • They can select elements regardless of their position in the parent element.
  • They can target elements with multiple classes.

Additional Resources:

  • [W3Schools: :last-of-type Selector](https://www.w3schools.com/cssref/sel_lastoftype.asp)
  • [CSS-Tricks: Understanding Attribute Selectors](https://css-tricks.com/attribute-selectors/)

The above is the detailed content of How to Select the Last Child Element with a Specific Class in CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template