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

如何用SCSS为类创建h1、h2、h3版本的样式?

修正SCSS嵌套写法实现元素+类选择器

你当前的SCSS写法会把父选择器.title和h1直接拼接成.titleh1,和你想要的h1.title不符。要实现目标样式,需要调整嵌套里选择器的结构,把元素选择器放在父选择器(&)前面:

.title {
  color: red;
    
  h1& {
    font-size: 18px;
  }
    
  h2& {
    font-size: 16px;
  }
}

编译后得到的CSS就是你预期的结果:

.title { 
  color: red; 
}
h1.title { 
  font-size: 18px; 
}
h2.title { 
  font-size: 16px; 
}

原理是&代表当前父选择器.title,h1&会被解析为h1.title,刚好符合你“标题元素同时包含.title类”的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:25:57