"Introducing Has: A Native CSS Parent Selector"

26 May 2023 Balmiki Kumar 0 MERN Full Stack

Introducing ‘:has’: A Native CSS Parent Selector

CSS selectors are powerful tools for developers and designers to target specific elements and apply styling. With the introduction of the new ':has' selector, web developers have access to an incredibly useful native parent selector that simplifies the way they write complex CSS rules.

What is the ‘:has’ Selector?

The :has() selector is a CSS pseudo-class that allows you to select an element's parent if it has a certain descendant. This means that you can target a specific element based on its parent, and not just based on its own attributes. This can be especially helpful when you want to target an element with more specificity without writing overly long CSS selectors. For example, before :has(), you might have had to write something like this in order to target all elements inside

elements that have the class “my-class”: ``` p.my-class span {} ``` But with the :has() selector, you can simplify this to one line: ``` p:has(.my-class) span {} ```

Why Should You Use the ‘:has’ Selector?

The :has selector can save you time when you need to target an element in a more specific way. If your HTML markup is complex, you may find that using this native selector can reduce the length of your CSS selectors, and make them easier to read. It also allows you to target elements based on their parents, which can give you greater CSS specificity without having to write additional elements in your selectors. On top of making your selectors shorter and more efficient, it can also make your code more maintainable. Keeping your selectors short and specific helps to keep them organized and easier to update or refactor in the future.

How Do You Use the ‘:has’ Selector?

Using the :has() selector is simple. Just add it to any existing CSS selector, followed by a content selector that will match the desired element. For example, to target all

elements that have a with the class “my-class”, you would write: ``` div:has(span.my-class) {} ``` You can also use the :has() selector in combination with other selectors to create even more specific targeting. For example, you could target all

elements inside

elements that contain s with the class “my-class” like this: ``` div p:has(span.my-class) {} ``` You can even use multiple :has() selectors to target multiple descendent elements. For example, to target all elements containing both a and a
, you can write: ``` :has(span, div) {} ```


The :has() selector is a powerful tool for targeting elements based on their parent elements. It can help you write shorter, more maintainable CSS selectors, and gives you greater specificity when targeting elements with complex HTML markup. Give the :has() selector a try in your next project—you won't regret it!

BY: Balmiki Kumar

Related News

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.