How to make Parent Div Activate Styling of Child Div for Hover and Active ?

In this article, we will see how to make parent div activate styling of child div for hover and active. We can do this by using Pseudo-classes like hover and active.
Approaches to make parent div activate styling of child div for hover and active
- Using Pure CSS: with pseudo-classes
- Using CSS and JavaScript: without pseudo-classes
Method 1: Using Pure CSS
Pseudo-class
Pseudo-classes are keywords used in CSS to define special states of HTML elements based on user interactions or element states without the need for additional classes or JavaScript.
- hover: This pseudo-class targets an element when the user hovers their mouse pointer over it.
- active: This pseudo-class targets an element when it’s being activated, usually by a user clicking on it.
Example: In this example, we will use CSS pseudo-selectors to make parent div activate styling of child div for hover and active.
HTML
<!DOCTYPE html> <html> <head> <style> .parent-div { width: 200px; height: 200px; background-color: lightgray; } .child-div { width: 100px; height: 100px; background-color: skyblue; margin: 50px; transition: background-color 0.3s; } .parent-div:hover .child-div { background-color: lightgreen; } .parent-div:active .child-div { background-color: coral; } </style> </head> <body> <div class="parent-div"> <div class="child-div">Hover and Click Me</div> </div> </body> </html> |
Output:
Method 2: Using CSS and JavaScript
Example: In this article, we will use CSS and JavaScript to make parent div activate styling of child div for hover and active.
HTML
<!DOCTYPE html> <html> <head> <style> .parent-div { width: 200px; height: 200px; background-color: lightgray; } .child-div { width: 100px; height: 100px; background-color: skyblue; margin: 50px; } .child-div.active { background-color: coral !important; } </style> </head> <body> <div class="parent-div"> <div class="child-div"> Hover and Click Me </div> </div> <script> const parentDiv = document.querySelector('.parent-div'); const childDiv = parentDiv.querySelector('.child-div'); parentDiv.addEventListener('click', () => { childDiv.classList.toggle('active'); }); parentDiv.addEventListener('mouseover', () => { childDiv.style.backgroundColor = 'lightgreen'; }); parentDiv.addEventListener('mouseout', () => { childDiv.style.backgroundColor = 'skyblue'; }); </script> </body> </html> |
Output:
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!




