CSS :has() Pseudo-class
Example
Style <h2> elements that are immediately followed by a <p> element:
color: gray;
background-color: gold;
border: 2px dotted red;
}
More "Try it Yourself" examples below.
Definition and Usage
The CSS :has() pseudo-class
matches any parent element that has a specific sibling or has a specific element
inside it.
Examples of use:
- Hide or show elements based specific siblings or on what is inside them
- Change the layout of things if specific content is present
- Make parent elements look different if they have certain types of siblings or content inside
| Version: | CSS4 |
|---|
Browser Support
The numbers in the table specifies the first browser version that fully supports the pseudo-class.
| Pseudo-class | |||||
|---|---|---|---|---|---|
| :has() | 105 | 105 | 121 | 15.4 | 91 |
CSS Syntax
css declarations;
}
More Examples
Example
Style <section> elements that have an <h1> element inside, and also style <section> elements that have an element with class 'funfact' inside:
background-color: gold;
}
section:has(.funfact) {
color: blue;
}
Example
Style <li> elements (in <ul>) with a checked <input> element inside:
border:2px solid maroon;
}