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

将CSS转为BEM规范SCSS:解决.carousel-button:hover箭头样式失效问题

符合BEM规范的正确SCSS写法

问题出在你嵌套hover时的子元素选择器写法错误,&arrow是无效语法,正确写法需要明确引用BEM元素类,同时利用SCSS父选择器&拼接正确的选择器结构。

以下是修正后的完整SCSS代码:

.carousel-button {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background-color: transparent;
  border: 1px solid var(--color-brand-dark);
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  flex-shrink: 0;

  &:hover {
    background-color: var(--color-brand-light);
    border: 1px solid white;

    // 正确写法:& 代表当前父选择器 .carousel-button:hover,拼接后为 .carousel-button:hover .carousel-button__arrow
    & &__arrow {
      fill: white;
    }
  }

  &__arrow {
    fill: var(--color-brand-dark);
    transition: fill 0.2s;
  }
}

为什么原来的写法无效?

  • &arrow没有遵循SCSS父选择器的拼接规则,会被解析成.carousel-button:hoverarrow,这显然不是目标选择器。
  • 注释里的.carousel-button:hover .arrow能生效,是因为直接指定了hover状态下的子元素,但不符合BEM规范。正确的BEM子元素类是.carousel-button__arrow,所以要用& &__arrow生成.carousel-button:hover .carousel-button__arrow这个合法选择器。

另一种等价写法

如果你觉得& &__arrow不够直观,也可以直接写后代选择器,效果完全一致:

&:hover {
  background-color: var(--color-brand-light);
  border: 1px solid white;

  .carousel-button__arrow {
    fill: white;
  }
}

不过更推荐& &__arrow的写法,这样修改块类名时,子元素选择器会自动同步,更符合SCSS的模块化优势。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 22:23:14