Home > Web Front-end > CSS Tutorial > 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
Release: 2024-11-26 04:12:08
Original
222 people have browsed it

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 */
}
Copy after login

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>
Copy after login

And the following CSS:

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

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!

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