DEV Community

Aliasger Ratlam
Aliasger Ratlam

Posted on

CSS selector for parent element? ๐Ÿคจ

Hello Fellow Coders! ๐Ÿ‘‹

Ever found yourself scratching your head over styling parent elements based on their child's class? Fear not, for here's a CSS trick that might just blow your mind!

The Solution:

Introducing :has() CSS pseudo-class a game-changer method to achieve the parent element appearance based on the child element.

Quick Explanation:

The :has() is a pseudo-class CSS that takes a selector as an argument. On your parent element add :has() pseudo-class CSS to target the element that matches the passed-in argument.

For Example:

Consider a simple small Card Box.

<div class="card">
    <h2>Hello World!</h2>
</div>
Enter fullscreen mode Exit fullscreen mode

Now you want to change the card appearance like adding a box-shadow. when child div has active class.

box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
Enter fullscreen mode Exit fullscreen mode

How can you do this? ๐Ÿคทโ€โ™‚๏ธ

You can add like this:

.card:has(h2.active) {
   box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
}
Enter fullscreen mode Exit fullscreen mode

Alternatively, You can achieve this using JavaScript to add or remove classes from the parent div based on the state of the child div. However, there is no need for JavaScript โ€“ just pure CSS magic! ๐Ÿคฉ

Happy coding! ๐Ÿ’ปโœจ

Top comments (0)