Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger hover effect on child elements when hovering over the parent div?

Currently, I am working on a nextJS web application and have some issue with the css. I have a div (parent node) and inside the div have multiple child elements. So whenever I hover over the parent div element, I want it to trigger on the child elements too.

For example this is a simplified version of my code

export default function portfolio() {
return (
    <div className={homeStyles.mainContent}>
        <div className={homeStyles.titleNum}>
            <h2>01</h2>
        </div>
        <div className={homeStyles.titleName}>
            <h2>Telegram Bot</h2>
        </div>
    </div>
    )
}

So whenever I hover over the parent div (.mainContent), it will change the background color as well as the child elements (Title Number and Title Name), will change font color and increase font size, simultaneously.

Can anyone enlighten me how to make it happen using nextJS. Thank you.

EDITED

Not sure does this works?

<div class="main">
      <div class="num">Num</div>
      <div class="name">Name</div>
</div>
.main {
  background: blue; 
}

.main:hover {
  background: green;
}

.main:hover .num,
.main:hover .name {
  color: red;
  font-weight: bold;
}

Is there a better way to do this? Because it look kind of messy especially when I have about 6 child elements to trigger in one go. Anyway to make the code more concise and slick?

like image 990
Cheechai Ong Avatar asked Oct 25 '25 04:10

Cheechai Ong


1 Answers

Add > after hover and then the .classname of the element that you wanna change.

  • This might not work in all cases. But with pure html and css, it works.

.parentClass{
    height: 300px;
    width: 300px;
    background-color: red;
}

.childClass{
    background-color: blue;
    height: 150px;
    width: 150px;
}

/* This is where you define the hover effect */
.parentClass:hover > .childClass {
    background-color: green;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Test</title>
</head>

<body>
    <div class="parentClass">
        <div class="childClass">

        </div>
    </div>
</body>

</html>
like image 66
Kasun Shanaka Avatar answered Oct 26 '25 19:10

Kasun Shanaka