Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In next.js, using css, how do I target a child element when its parents is hovered over?

This is the css that targets the child element, "#overlay", when the parent, ".collection", is hovered.

.collection {
    position: relative;
    overflow: hidden;
}

.collection:hover #overlay { 
    position: absolute;
    opacity: .3;
}

This is the html:

import styles from "./Home.module.css";

<div className={`${styles.collection} card`}>
    <div id="overlay"></div>
</div>

The properties are not applied to the child element when the parent is hovered.

like image 336
koque Avatar asked Oct 31 '25 09:10

koque


1 Answers

The problem is that by default Next.js uses css module when importing css from Components, that means that import of css will return an object with class & id map to uglified strings.

You need to use class selector and use it on the child component.

.collection {
    position: relative;
    overflow: hidden;
}

.collection:hover .overlay { 
    // -----------^
    position: absolute;
    opacity: .3;
}
import styles from "./Home.module.css";

<div className={`${styles.collection} card`}>
    <div id="overlay" className={styles.overlay}></div>
    // --------------------------------^
</div>
like image 148
felixmosh Avatar answered Nov 03 '25 00:11

felixmosh