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>
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;
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;
}
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)