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

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

Susan Sarandon
Release: 2024-12-21 15:29:14
Original
908 people have browsed it

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

Selecting the "Last Child" with a Specific Class Name in CSS

When working with CSS, it can be crucial to select specific elements based on their position and class names. This question explores how to target the "last child" element with a particular class name.

Problem:

Consider the following HTML structure:

<ul>
    <li>
Copy after login

The goal is to select the last child that has the class name "list" and apply a specific style to it.

Proposed Solution (that doesn't work):

ul li.list:last-child{background-color:#000;}
Copy after login

Drawback:

The proposed solution is incorrect because CSS does not support the :last-child selector for elements with classes.

Working Solution:

The issue can be resolved using an attribute selector:

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

Explanation:

  • [class~=list]: This attribute selector matches elements that have the class name "list" or any other class name containing the string "list."
  • :last-of-type: This pseudo-class selects the last element of a particular type, in this case, the li element.

Advantages:

  • It works even when the "list" class is not the last class on the element.
  • It doesn't require knowledge of the exact position of the target element.

Important Notes:

  • Avoid using ul li:nth-child(3) as the number of children can vary.
  • JavaScript is not permitted for this solution.

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