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

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

Mary-Kate Olsen
Release: 2024-11-28 02:32:13
Original
956 people have browsed it

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

Styling Parent Elements Based on Child Elements

It's possible to define CSS styles for an element that are applied based on the presence of specific child elements. This is achieved using the :has() pseudo-class.

Example

Consider the following HTML:

<div>
  <div class="a"></div>
</div>

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

To style the parent div based on its children, use the :has() pseudo-class:

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

The first div will have a red border because it contains a child div with class "a". The second div will have a blue border because it contains a child div with class "b".

Note: Prior to the :has() pseudo-class, this behavior could only be achieved using JavaScript.

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