Home >Web Front-end >CSS Tutorial >Can You Select the Last Child Element Without a Specific Class in CSS?

Can You Select the Last Child Element Without a Specific Class in CSS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-19 04:07:33982browse

Can You Select the Last Child Element Without a Specific Class in CSS?

Combining the :last-child and :not(.class) Selectors in CSS

In CSS, can one select the last child element that lacks a specified class? For instance, considering the following HTML structure:

<tr class="table_vert_controls"> ... </tr>
<tr class="table_vert_controls"> ... </tr>
<tr class="table_vert_controls"> ... </tr>
<tr> ... </tr>

How can you select only the fourth row using CSS selectors? Attempting to use the following selector would not suffice:

tr:not(.table_vert_controls):last-child

Unfortunately, it is not feasible to achieve this using CSS selectors alone. The :last-child pseudo-class specifically targets the very last child, and there is no comparable :last-of-class pseudo-class.

As of 2015, Selectors 4 introduced an extension to :nth-child() and :nth-last-child() selectors, enabling the use of arbitrary selectors as arguments. This would permit the following syntax:

tr:nth-last-child(1 of :not(.table_vert_controls))

However, as of April 2018, only Safari supports this feature, so widespread compatibility is still several years away.

Alternative Approaches:

In the interim, alternative methods must be employed:

  • Adding an Extra Class: Add a class immediately preceding the target class, and then select the last child with that new class.
  • jQuery Selector: Use the jQuery selector:
$('tr:not(.table_vert_controls):last')

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

Statement:
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