简体   繁体   中英

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM