You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js CSS模块中Sass嵌套选择器异常问题求助

问题根源与解决方案

这不是Bug,是对Next.js CSS模块的局部作用域机制不熟悉导致的。

核心原因

Next.js CSS模块会自动给所有自定义类名添加唯一哈希后缀(比如.mobile_menu会变成.mobile_menu_abc123),以此实现样式隔离。但以下两种情况会导致选择器匹配失败:

  1. react-bootstrap这类第三方组件自带的类名(比如btn-close)是全局类名,不会被CSS模块添加哈希;
  2. 你手动添加的active类是全局类名,同样不会被哈希。

你写的嵌套选择器里的.btn-close、.active会被CSS模块当成局部类名处理,自动添加哈希后缀,导致编译后的选择器无法匹配DOM上的原始类名。

至于纯元素选择器(比如h1、button)能生效,是因为CSS模块不会给元素选择器添加哈希,所以编译后的选择器(比如.mobile_menu_title_abc123 h1)能正确匹配DOM元素。


具体修复方案

1. 修复button.btn-close样式不生效问题

将btn-close用:global()包裹,告诉CSS模块这是全局类名,不要添加哈希:

.mobile_menu_header {
    border-bottom: solid 1px rgb(148, 162, 170);

    button:global(.btn-close) {
        filter: brightness(0) invert(1) !important;
        opacity: 1 !important;
        width: 1.6rem !important;
        height: 1.6rem !important;
        background-size: 100% !important;
    }
}

同样用:global()包裹active类:

.link {
    color: #fff;
    text-transform: uppercase;
    font-size: 1.7rem;
    transition: color 0.3s ease-in-out;

    &:global(.active) {
        border-bottom: solid 1rem rgb(148, 162, 170) !important;
    }

    &:hover {
        color: rgb(148, 162, 170);
    }
}

内容的提问来源于stack exchange,提问作者RBFraphael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 14:50:28