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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series ๐Ÿ“บ

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series ๐Ÿ‘€

Watch the Youtube series