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

如何用:has与:not选择器为非.modal父元素下的.simple-checkbox-options加样式?

解决方法

你的SCSS代码问题出在选择器逻辑和语法上,以下是修正后的写法:

核心错误说明

  1. 嵌套逻辑颠倒:&作为父选择器(即.simple-checkbox-options),应该被外层选择器包裹,而不是反过来
  2. :not语法错误:正确写法是:not(.modal),而非.modal:not
  3. 不需要用:has:你的需求是父元素本身不带.modal类,直接用:not(.modal)选择父元素即可

情况1:直接父元素不带.modal类

如果仅要求直接父元素没有.modal类时应用样式,使用子选择器>:

.simple-checkbox-options {
  :not(.modal) > & {
    display: grid;
    grid-column-gap: 20px;
    grid-row-gap: 20px;
  }
}

展开后的原生CSS:

:not(.modal) > .simple-checkbox-options {
  display: grid;
  grid-column-gap: 20px;
  grid-row-gap: 20px;
}

情况2:任何祖先元素都不带.modal类

如果要求整个祖先链中没有带.modal类的元素,去掉子选择器>即可:

.simple-checkbox-options {
  :not(.modal) & {
    display: grid;
    grid-column-gap: 20px;
    grid-row-gap: 20px;
  }
}

展开后的原生CSS:

:not(.modal) .simple-checkbox-options {
  display: grid;
  grid-column-gap: 20px;
  grid-row-gap: 20px;
}

额外补充:如果是父元素不含.modal类的子元素

如果你的实际需求是父元素内部没有任何带.modal类的子元素(而非父元素本身不带类),才需要用到:has选择器,写法如下:

.simple-checkbox-options {
  :not(:has(.modal)) & {
    display: grid;
    grid-column-gap: 20px;
    grid-row-gap: 20px;
  }
}

注意::has选择器仅支持现代浏览器,旧版浏览器(如IE)无法兼容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:02:07