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

如何优化该场景下的SCSS代码?减少重复的多种方案

减少SCSS代码重复的高效方案(针对同样式仅背景色差异的元素)

你有两个类app__footer-card-email和app__footer-card-mobile,仅背景色不同,其余样式完全一致。以下是几种SCSS代码复用的高效方法,可推广到其他相似场景:


方法1:群组选择器(基础简洁方案)

将公共样式提取到群组选择器中,仅单独定义差异化属性:

.app__footer-card-email,
.app__footer-card-mobile {
  width: 360px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 2rem;
  opacity: 0.7;
  border-radius: 10px;
  padding: 10px;
  flex-direction: row;
}

.app__footer-card-email {
  background-color: #ffc9d0;
}

.app__footer-card-mobile {
  background-color: #d0e2fe;
}

适用场景:差异化属性极少(仅1-2个)的简单场景,代码直观,维护成本低。


方法2:占位符选择器+@extend(无冗余编译方案)

用占位符定义公共样式(不会被编译到最终CSS),再通过@extend继承:

%footer-card-base {
  width: 360px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 2rem;
  opacity: 0.7;
  border-radius: 10px;
  padding: 10px;
  flex-direction: row;
}

.app__footer-card-email {
  @extend %footer-card-base;
  background-color: #ffc9d0;
}

.app__footer-card-mobile {
  @extend %footer-card-base;
  background-color: #d0e2fe;
}

适用场景:公共样式需要在多个元素中复用,且不想生成冗余CSS代码的场景。


方法3:混合宏@mixin+参数传递(动态扩展方案)

定义带参数的混合宏,将差异化属性作为参数传入,支持后续灵活扩展:

@mixin footer-card($bg-color) {
  width: 360px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 2rem;
  opacity: 0.7;
  border-radius: 10px;
  padding: 10px;
  flex-direction: row;
  background-color: $bg-color;
}

.app__footer-card-email {
  @include footer-card(#ffc9d0);
}

.app__footer-card-mobile {
  @include footer-card(#d0e2fe);
}

适用场景:后续可能增加更多差异化属性(如边框色、文字色)的场景,扩展性强。


方法4:多类名优化(结合HTML结构)

修改HTML为元素添加公共类,用公共类写基础样式,差异化类定义特殊属性:

修改后的HTML

const Footer = () => {
  return (
    <>
    <div className="app__footer">
    <h3 className="head-text">Want to reach out?</h3>
    <h3 className="head-text">Lets have a chat over some coffee.</h3>

    <div className="app__footer-cards">
      <div className="app__footer-card app__footer-card-email">
        <img src={images.email} alt="email"/>
        <a href="edwin.huang9@gmail.com">edwin.huang9@gmail.com</a>
      </div>
      <div className="app__footer-card app__footer-card-mobile">
        <img src={images.mobile} alt="mobile"/>
        <a href="0415560320">0415560320</a>
      </div>
    </div>
    </div>
    </>
  )
}

对应的SCSS

.app__footer-card {
  width: 360px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 2rem;
  opacity: 0.7;
  border-radius: 10px;
  padding: 10px;
  flex-direction: row;
}

.app__footer-card-email {
  background-color: #ffc9d0;
}

.app__footer-card-mobile {
  background-color: #d0e2fe;
}

适用场景:需要在多个模块复用基础样式,同时保持差异化类语义性的场景,CSS逻辑更清晰。


内容的提问来源于stack exchange,提问作者Edwin Huang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:25:27