Home > Web Front-end > CSS Tutorial > How Does the CSS `:last-child` Selector Work, and When Should I Use `:last-of-type` Instead?

How Does the CSS `:last-child` Selector Work, and When Should I Use `:last-of-type` Instead?

DDD
Release: 2024-12-11 20:07:27
Original
792 people have browsed it

How Does the CSS `:last-child` Selector Work, and When Should I Use `:last-of-type` Instead?

Understanding the :last-child Selector

The :last-child selector is used to target the last child element of a parent. However, there are some important subtleties to be aware of in its usage.

Exclusion of Elements Outside of Direct Parent

One crucial point to note is that the :last-child selector will not target elements if they are not the last child of their immediate parent. This means that if an element has any other siblings, whether nested or not, :last-child will not apply to it.

Example

Consider the following HTML and CSS:

<ul>
    <li class="complete">1</li>
    <li class="complete">2</li>
    <li>3</li>
    <li>4</li>
</ul>
Copy after login
li.complete:last-child {
    background-color: yellow;
}
Copy after login

In this scenario, neither li element with the "complete" class will have a yellow background. This is because they are not the very last child of the

    element. The
  • element with the value "4" comes after the second "complete"
  • , making it the last child.

    Alternative Selectors

    To target the last child of a group of sibling elements, :last-of-type can be used instead. It selects the last instance of an element type within its parent, regardless of any other elements present.

    jQuery Considerations

    The jQuery selector $("li.complete:last-child") will also not target the desired element, as it behaves similarly to the CSS selector. However, $("li.complete").last() will select the last element in the list, regardless of its position relative to other siblings.

    Conclusion

    Understanding the nuances of :last-child is essential for accurate element targeting. Always ensure that the element is the last child of its direct parent if you intend to use this selector. Alternatively, :last-of-type can be a useful choice when selecting the last instance of an element type within a parent container.

    The above is the detailed content of How Does the CSS `:last-child` Selector Work, and When Should I Use `:last-of-type` Instead?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template