Home  >  Article  >  Web Front-end  >  How Can I Style a Parent Element Based on the Existence of a Specific Child Element in CSS?

How Can I Style a Parent Element Based on the Existence of a Specific Child Element in CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 04:12:08137browse

How Can I Style a Parent Element Based on the Existence of a Specific Child Element in CSS?

Apply Style to Parent if it Has Child with CSS

In CSS, styling the parent element based on its child elements' existence can be achieved using the has() selector.

To apply styles to the parent when it contains a child with the class "sub," use the following CSS rule:

ul li:has(ul.sub) {
  /* Parent styles */
}

For example, if you have the following HTML:

<ul class="main">
  <li>Parent 1</li>
  <li>Parent 2</li>
  <li>Parent 3 with Child
    <ul class="sub">
      <li>Child of Parent 3</li>
    </ul>
  </li>
  <li>Parent 4</li>
</ul>

And the following CSS:

ul li:has(ul.sub) {
  background-color: lightblue;
}

The output will show "Parent 3 with Child" in light blue, indicating that the parent (li) has a child with the class "sub."

Note that the $ selector mentioned in the question's proposed answer is not yet standardized in CSS4. Instead, the has() selector is the supported way to achieve this functionality.

The above is the detailed content of How Can I Style a Parent Element Based on the Existence of a Specific Child Element 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