Home >Web Front-end >CSS Tutorial >How to Style a Parent Element Based on its Child Elements with CSS?

How to Style a Parent Element Based on its Child Elements with CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 17:45:17860browse

How to Style a Parent Element Based on its Child Elements with CSS?

How to Apply Style to Parent Element if it Has a Child with CSS

In web development, it's often necessary to apply specific styling to elements based on their relationship with other elements in the DOM. One particular challenge is styling parent elements if they contain child elements.

Consider the following HTML structure:

<ul class="main">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>
        <ul class="sub">
            <li>Sub Item 1</li>
            <li>
                <ul>
                    <li>Sub Sub Item 1</li>
                    <li>Sub Sub Item 2</li>
                    <li>Sub Sub Item 3</li>
                </ul>
            </li>
            <li>Sub Item 3</li>
            <li>Sub Item 4</li>
            <li>Sub Item 5</li>
        </ul>
    </li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
</ul>

To style in CSS the

  • elements that have child
      elements, you can use the :has() selector:

      ul li:has(ul.sub) {
          background-color: yellow;
          border: 1px solid black;
      }

      By applying the background-color and border properties to li elements that meet the :has(ul.sub) condition, you can differentiate them from li elements that do not have any child ul.sub elements.

      It's important to note that the :has() selector is not supported in all browsers, so using this approach may require browser compatibility considerations.

      The above is the detailed content of How to Style a Parent Element Based on its Child Elements with 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