Home > Web Front-end > CSS Tutorial > How to Style the Last Child with a Specific Class Name using CSS?

How to Style the Last Child with a Specific Class Name using CSS?

Susan Sarandon
Release: 2024-12-18 03:26:14
Original
612 people have browsed it

How to Style the Last Child with a Specific Class Name using CSS?

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

When working with CSS selectors, the task of targeting the last child of an element with a specific class can sometimes arise. Consider the following HTML:

<ul>
    <li class="list">test1</li>
    <li class="list">test2</li>
    <li class="list">test3</li>
    <li>test4</li>
</ul>
Copy after login

Our goal is to apply a style to the last child of the

  • elements with the class "list". The common approach of using ul li:nth-child(3) may not always be applicable, as the position of the desired element may vary.

    To overcome this issue, we can leverage attribute selectors. Here's how:

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

    In this selector:

    • [class~='list'] targets all elements whose class attribute contains the string "list" as a whole word. This allows for multiple classes with "list" anywhere in the string, regardless of order.
    • :last-of-type selects the last match of the previous selector within its type. In this case, it targets the last
    • element with the class "list".

    By combining these selectors, we can effectively style the last child of the specified class. You can find a рабочее, приятное demonstration at http://codepen.io/chasebank/pen/ZYyeab.

    For further reference on attribute selectors, check out the following resources:

    • http://css-tricks.com/attribute-selectors/
    • http://www.w3schools.com/css/css_attribute_selectors.asp

    The above is the detailed content of How to Style the Last Child with a Specific Class Name using 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