CSS :has() Pseudo-class
Example
Style <h2> elements that are immediately followed by a <p> element:
h2:has(+ p) {
color: gray;
background-color: gold;
border: 2px dotted red;
}
Try it Yourself »
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
:has(relative-selector-list) {
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:
section:has(h1) {
background-color: gold;
}
section:has(.funfact)
{
color: blue;
}
Try it Yourself »
Example
Style <li> elements (in <ul>) with a checked <input> element inside:
ul li:has(input:checked) {
border:2px solid maroon;
}
Try it Yourself »