Home > Web Front-end > CSS Tutorial > How Can I Style Parent Elements Based on Their Child Content Using CSS?

How Can I Style Parent Elements Based on Their Child Content Using CSS?

Linda Hamilton
Release: 2024-11-29 02:05:14
Original
566 people have browsed it

How Can I Style Parent Elements Based on Their Child Content Using CSS?

Target Elements Based on Child Content with CSS

You may encounter the need to apply unique CSS styles to parent elements based on the child elements they contain. While traditional CSS selectors focus on targeting specific elements, there is a way to achieve conditional styling using the :has() selector.

The syntax for :has() is as follows:

div:has(div.a) {
  border: solid 3px red;
}
div:has(div.b) {
  border: solid 3px blue;
}
Copy after login

With this syntax, you can apply styles to div elements that contain specific child elements. For instance, the above rules would add a red border to div elements containing a child with the class "a" and a blue border to div elements containing a child with the class "b".

Example:

<style>
  div:has(div.a) {
    border: solid 3px red;
  }
  div:has(div.b) {
    border: solid 3px blue;
  }
</style>
<div>
  <div class="a"></div>
</div>

<div>
  <div class="b"></div>
</div>
Copy after login

This code would result in two div elements, one with a red border and one with a blue border, corresponding to the child elements they contain.

Note: The :has() selector is widely supported in modern browsers but may not work in older browsers.

The above is the detailed content of How Can I Style Parent Elements Based on Their Child Content 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