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 for more specific and dynamic styling and can be used in conjunction with other pseudo-classes and selectors.

The :has() pseudo-class is used to select parent elements that contain specific child elements. This allows for conditional styling based on the presence or absence of certain children. The :not() pseudo-class can also be used in conjunction with :has() to select elements that do not have certain children.

Syntax:

:has()

Usage Examples

Example 1: Selecting Elements with Specific Children

This example selects all div elements that have a p element as a child and applies a specific style to them.

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>w3wiki</p>
    </div>
    <div>
        <h1>w3wiki</h1>
    </div>
</body>
 
</html>

Output: 

CSS :has() pseudo-class Selector

Example 2: Selecting Elements without Specific Children

This example selects all div elements that do not have a p element as a child and applies a specific style to them.

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>w3wiki</p>
    </div>
    <div>
        <h1>w3wiki</h1>
    </div>
</body>
 
</html>

Output:

CSS :has() pseudo-class Selector

The :has() pseudo-class in CSS is a highly useful addition for developers looking to apply styles conditionally based on the presence of child elements. Its ability to work in conjunction with other pseudo-classes and selectors makes it a versatile tool for modern web development. Ensure that the target browsers support this feature to avoid compatibility issues.

Supported Browsers

The :has() pseudo-class is supported by the following browsers:

  • Google Chrome (version 105 and above)
  • Edge (version 105 and above)
  • Opera (version 91 and above)
  • Safari (version 15.4 and above)
  • Firefox (not supported as of the latest update)


Contact Us