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! πŸ’»βœ¨

Neon image

Serverless Postgres in 300ms (!)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free β†’

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

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

Get started β†’

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay