Open In App

CSS :is() Selector

Last Updated : 09 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The CSS :is() pseudo-class selector allows you to group multiple selectors into one, selecting elements that match any of the specified selectors.

  • Simplifies code by reducing redundancy in selector definitions.
  • Useful for applying styles to multiple elements with shared properties.
  • Improves efficiency and readability in complex stylesheets.

Syntax:

:is()
HTML
<!--Driver Code Starts{-->
<html>
<head>
<!--Driver Code Ends }-->

    <style>
        :is(h1, h2) {
            color: blue;
        }
    </style>

<!--Driver Code Starts{-->
</head>
<body>
    <h1>Heading 1</h1>
    <h2>Heading 2</h2>
    <p>This is a paragraph.</p>
</body>
</html>

<!--Driver Code Ends }-->
  • The :is() pseudo-class simplifies the CSS by grouping multiple selectors (h1, h2) into a single rule.
  • All <h1>, <h2> elements are styled with a blue color, reducing redundancy in the stylesheet.

More Example of CSS

Styling Multiple Elements with a Single Rule

HTML
<!--Driver Code Starts{-->
<html>
<head>
<!--Driver Code Ends }-->

    <style>
        :is(h1, h2, h3) {
            color: blue;
        }
    </style>

<!--Driver Code Starts{-->
</head>
<body>
    <h1>Heading 1</h1>
    <h2>Heading 2</h2>
    <h3>Heading 3</h3>
    <p>This is a paragraph.</p>
</body>
</html>

<!--Driver Code Ends }-->

In this example:

  • The :is() pseudo-class simplifies the CSS by grouping multiple selectors (h1, h2, h3) into a single rule.
  • All <h1>, <h2>, and <h3> elements are styled with a blue color, reducing redundancy in the stylesheet.

Applying Styles to Multiple Classes

HTML
<!--Driver Code Starts{-->
<html>
<head>
<!--Driver Code Ends }-->

    <style>
        :is(.note, .alert) {
            background-color: lightgray;
            padding: 10px;
            border-radius: 5px;
        }
    </style>

<!--Driver Code Starts{-->
</head>
<body>
    <div class="note">This is a note.</div>
    <div class="alert">This is an alert.</div>
    <div class="message">This is a message.</div>
</body>
</html>

<!--Driver Code Ends }-->

In this example:

  • The :is() pseudo-class groups the .note and .alert classes, applying the same styles to both.
  • Elements with either class receive a light gray background, padding, and rounded corners, demonstrating efficient styling of multiple classes.

Best Practices for Using the CSS :is() Selector

  • Simplify Complex Selectors: Use :is() to group multiple selectors, reducing redundancy and enhancing readability.
  • Be Mindful of Specificity: The :is() selector adopts the specificity of its most specific argument. Ensure this behavior aligns with your styling intentions to avoid unexpected overrides.
  • Ensure Browser Compatibility: While :is() is supported in modern browsers, verify compatibility, especially if supporting older versions.


Next Article

Similar Reads