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

CSS Modules报错:button选择器非纯净的问题求助

解决CSS Modules中"Selector 'button' is not pure"报错问题

这个报错的核心原因是CSS Modules强制要求选择器必须包含本地类或ID,不允许直接使用标签选择器(如button),目的是保证样式的局部作用域,避免全局样式污染。

方案一:使用类选择器(推荐)

给按钮添加类名,修改React组件和CSS代码:

  1. 修改React组件代码:
    给button标签添加className,关联CSS Modules中的类:
<button className={styles.resetButton} onClick={() => resetBoard()}>
    Reset Board
</button>
  1. 修改app.module.css代码:
    将所有button标签选择器替换为类选择器.resetButton,包括伪类和媒体查询中的选择器:
.resetButton {
    background-color: #111827;
    border: 1px solid transparent;
    border-radius: .75rem;
    box-sizing: border-box;
    color: #FFFFFF;
    cursor: pointer;
    flex: 0 0 auto;
    font-family: "Inter var";
    font-size: 1.125rem;
    font-weight: 600;
    line-height: 1.5rem;
    padding: .75rem 1.2rem;
    text-align: center;
    text-decoration: none #6B7280 solid;
    text-decoration-thickness: auto;
    transition-duration: .2s;
    transition-property: background-color, border-color,
        color, fill, stroke;
    transition-timing-function: cubic-bezier(.4, 0, 0.2, 1);
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
    width: auto;
}

.resetButton:hover {
    background-color: #374151;
}

.resetButton:focus {
    box-shadow: none;
    outline: 2px solid transparent;
    outline-offset: 2px;
}

@media (min-width: 768px) {
    .resetButton {
        padding: .75rem 1.5rem;
    }
}

方案二:使用全局选择器(不推荐)

如果一定要保留标签选择器,可以用CSS Modules的:global()伪类将样式声明为全局,但这会失去CSS Modules局部作用域的优势,可能引发样式冲突:

:global(button) {
    background-color: #111827;
    /* 其他样式属性 */
}

:global(button:hover) {
    background-color: #374151;
}

:global(button:focus) {
    box-shadow: none;
    outline: 2px solid transparent;
    outline-offset: 2px;
}

@media (min-width: 768px) {
    :global(button) {
        padding: .75rem 1.5rem;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:47:54