Home > Web Front-end > CSS Tutorial > How to Style the Last Child Element with a Specific Class Name Using Only CSS?

How to Style the Last Child Element with a Specific Class Name Using Only CSS?

Susan Sarandon
Release: 2024-12-30 22:16:14
Original
193 people have browsed it

How to Style the Last Child Element with a Specific Class Name Using Only CSS?

Selecting the Last Child with a Specific Class Name in CSS

In search of a CSS solution to target the last child element with a specific class name, the question poses a challenge because the number of child elements can vary. This arises the concern that nth-child() may not be sufficient. JavaScript is also ruled out as an option.

The solution lies in the :last-of-type pseudo-class and attribute selectors.

CSS Code:

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

Explanation:

  • [class~="list"]: Selects elements that have the class name "list" as part of their class attribute value (i.e., not necessarily as the only class).
  • :last-of-type: Selects elements that are the last child of their type (i.e., the last li element with the class "list").

By combining these selectors, the rule applies a black background to the last child element that has the class name "list," regardless of whether it has other classes or how many child elements are present.

Example:

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

In this example, even though the third child has an additional class, the CSS rule will still apply the black background to it because it is the last child with the class name "list."

Attribute Selectors:

Attribute selectors allow us to target elements based on their attributes, including class names. The class~ selector allows us to select elements that have a class name that contains a specified word (e.g., if we had multiple classes named "list-item-1," "list-item-2," etc.).

Resources:

  • [CSS Attribute Selectors](http://css-tricks.com/attribute-selectors/)
  • [W3Schools Attribute Selectors](http://www.w3schools.com/css/css_attribute_selectors.asp)

The above is the detailed content of How to Style the Last Child Element with a Specific Class Name Using Only 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template