skip to Main Content

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?

2

Answers


  1. You can use these CSS rules :

    .main {
      background-color: #ccc;
    }
    
    .main:hover {
      background-color: #aaa;
    }
    
    .main:hover > div {
      color: red;
      font-weight: bold;
    }
    <div class="main">
      <div class="num">Num</div>
      <div class="name">Name</div>
    </div>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search