DEV Community

Aliasger Ratlam
Aliasger Ratlam

Posted on

1

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! ๐Ÿ’ปโœจ

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free โ†’

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay