Home >Web Front-end >CSS Tutorial >How to Style the Last Child Element with a Specific Class Name in CSS?
Selecting the "Last Child" with a Specific Class Name in CSS
In the realm of CSS styling, it's often necessary to manipulate elements based on their position within their parent container. The challenge arises when we need to target the "last child" of an element with a specific class name.
Consider the following HTML structure:
<ul> <li class="list">test1</li> <li class="list">test2</li> <li class="list">test3</li> <li>test4</li> </ul>
The goal is to apply a style to the last
Attribute Selectors to the Rescue
CSS attribute selectors allow us to target elements based on specific attributes. In this case, we can use the [class~='list'] selector to target elements that have the class "list". The "~=" operator matches an element that has the specified class as a whole word. This allows for flexibility in class naming conventions, ensuring that multiple classes are considered.
Finally, the :last-of-type pseudo-class selects the last child of its type that matches the preceding selector. Combining these techniques produces the following working selector:
[class~='list']:last-of-type { background: #000; }
This selector will match the last
Learn More About Attribute Selectors:
The above is the detailed content of How to Style the Last Child Element with a Specific Class Name in CSS?. For more information, please follow other related articles on the PHP Chinese website!