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; }
Explanation:
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>
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:
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!