f024171e26d661874252
·2 min read

Understanding CSS Selectors: :has, :is, and :where

css
pseudo class
4d5fd787ac74e0caa4f7

Sohan R. Emon

Developer, Learner, Tech Enthusiast

When it comes to styling web pages with CSS, selectors play a pivotal role in targeting and applying styles to specific elements. Three relatively new pseudo-classes—:has, :is, and :where—have been introduced to the CSS world, each with its unique purpose. In this brief guide, we'll explore the key differences between these selectors.

:has

The :has pseudo-class is used to select an element if it contains a certain element or elements that match the specified selector. It's particularly handy for selecting parent elements based on the content they contain. For example, if you want to style all <div> elements that contain an <a> tag, you can use div:has(a).

css
div:has(a) {
  /* Your styles here */
}

:is

The :is pseudo-class allows you to select elements that match a given selector. It's useful for simplifying complex selectors and improving code readability. For instance, to select all headings (<h1>, <h2>, <h3>, etc.) in an article, you can use :is(h1, h2, h3).

css
:is(h1, h2, h3) {
  /* Your styles here */
}

:where

The :where pseudo-class is quite similar to :is, but it's designed to have a lower specificity, making it useful for overruling more specific styles. It selects elements that match the given selector but does not increase the specificity of the selector. This can be helpful for creating more flexible styles.

css
:where(h1, h2, h3) {
  /* Your styles here */
}

These three pseudo-classes provide CSS developers with powerful tools for targeting and styling elements. :has is great for selecting based on content, :is simplifies complex selectors, and :where allows for flexible styling without increasing specificity.

Found this useful?