You need to enable JavaScript to run this app. CSS中是否有类似类的可复用样式功能避免重复编写相同样式
优惠活动
大模型
产品
解决方案
定价
更多

CSS中是否有类似类的可复用样式功能避免重复编写相同样式

你写的@class定义、style: @class引用的语法不属于原生CSS的标准规范,无法在浏览器中直接运行,你想要实现的「抽离公共样式复用、避免重复代码」的需求,有以下几种正确的实现方式:

方案1:使用公共类(原生CSS,兼容性最好)

直接给所有需要复用样式的元素加上同一个公共类,把公共样式写在公共类名下,单独的样式分别定义即可:

<!DOCTYPE html>
<body>
  <div class="base-row row1">1</div>
  <div class="base-row row2">2</div>
  <div class="base-row row3">3</div>
<style>
  .base-row {
    color: white;
    border-radius: 5px;
    height: 20px;
    width: 40px; 
  }
  .row1{
    background: red;
  }
  .row2{
    background: green;
  }
  .row3{
    background: grey;
  }
</style>
</body>
</html>

方案2:使用:is()选择器批量设置公共样式(原生CSS,现代浏览器支持)

如果不想修改HTML的类名,可以用CSS的:is()伪类把所有需要复用样式的选择器归为一组,统一声明公共属性:

<!DOCTYPE html>
<body>
  <div class="row1">1</div>
  <div class="row2">2</div>
  <div class="row3">3</div>
<style>
  :is(.row1, .row2, .row3) {
    color: white;
    border-radius: 5px;
    height: 20px;
    width: 40px; 
  }
  .row1{
    background: red;
  }
  .row2{
    background: green;
  }
  .row3{
    background: grey;
  }
</style>
</body>
</html>

方案3:使用CSS预处理器的混合宏(适合工程化项目)

如果你在工程化项目中使用SCSS这类CSS预处理器,可以用@mixin实现你设想的抽离复用逻辑,写法和你原本的思路最接近:

// 定义公共样式混合宏
@mixin base-row {
  color: white;
  border-radius: 5px;
  height: 20px;
  width: 40px; 
}
.row1{
  @include base-row;
  background: red;
}
.row2{
  @include base-row;
  background: green;
}
.row3{
  @include base-row;
  background: grey;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 02:36:08