CSS :has() pseudo-class Selector
The CSS :has() pseudo-class is a relatively new feature that allows developers to select elements based on their children. It is a powerful tool that allows for more specific and dynamic styling, and can be used in conjunction with other pseudo-classes and selectors.
The :has() pseudo-class is used by placing it before a selector, followed by the children that the parent element should have. It is also possible to use :not() in conjunction with :has() to select elements that do not have certain children.
Syntax:
:has()
Example 1: The following code will select all div elements that have a p element as a child and give it the respective style which is mentioned in the style tag.
HTML
<!DOCTYPE html> < html > < head > < title >CSS :has() Selector</ title > < style > body{ text-align: center; display: flex; justify-content: center; align-items:center; flex-direction: column; } div:has(p) { color: green; border: 2px solid green; width: 20vw; } </ style > </ head > < body > < div > < p >GeeksforGeeks</ p > </ div > < div > < h1 >GeeksforGeeks</ h1 > </ div > </ body > </ html > |
Output:

CSS :has() pseudo-class Selector
Example 2: The following code will select all div elements that do not have a p element as a child and give it the respective style which is mentioned in the style tag.
HTML
<!DOCTYPE html> < html > < head > < title >CSS :has() Selector</ title > < style > body{ text-align: center; display: flex; justify-content: center; align-items:center; flex-direction: column; } div:not(:has(p)) { color: green; border: 2px solid green; width: 20vw; } </ style > </ head > < body > < div > < p >GeeksforGeeks</ p > </ div > < div > < h1 >GeeksforGeeks</ h1 > </ div > </ body > </ html > |
Output:

CSS :has() pseudo-class Selector
Please Login to comment...