真正可复用的按钮组件必须将所有视觉变量抽成参数,如@button-base($bg, $color, $padding, $border-radius);状态变体用两层内嵌套伪类;尺寸与形状应拆分为正交mixin;CSS自定义属性仅用于JS需动态读取的变量。

按钮基础样式用 @mixin 封装,别写死颜色和尺寸
硬编码 $primary-color 或固定 16px 字体在 Sass 中等于放弃扩展性。真正可复用的按钮组件必须把所有视觉变量抽成参数。比如:
@mixin button-base($bg: #007bff, $color: white, $padding: 0.5em 1em, $border-radius: 4px) {
display: inline-flex;
align-items: center;
justify-content: center;
padding: $padding;
background-color: $bg;
color: $color;
border: none;
border-radius: $border-radius;
font-weight: 600;
cursor: pointer;
transition: background-color 0.2s;
}这样调用时才能灵活覆盖:@include button-base($bg: #28a745, $padding: 0.75em 1.5em);。漏掉默认值或把 $border-radius 写成固定像素,后续想适配圆角按钮就只能重写整个 mixin。
状态变体用 &:hover、&:disabled 等伪类嵌套,但别过度嵌套
Sass 嵌套能减少重复选择器,但嵌套超过三层就会让 CSS 输出膨胀、调试困难。按钮的状态逻辑应控制在两层以内:
@mixin button-variant($hover-bg, $disabled-bg) {
&:hover {
background-color: $hover-bg;
}
&:disabled {
background-color: $disabled-bg;
cursor: not-allowed;
opacity: 0.6;
}
}注意:不要写成 &:hover:hover 这类无效写法;:disabled 在 Firefox 中对 button 元素生效,但对 a 标签需配合 pointer-events: none 才可靠;如果项目要支持深色模式,:is([data-theme="dark"]) & 比全局切换更可控。
尺寸与形状通过独立 @mixin 组合,避免单个 mixin 越来越胖
把尺寸(small / medium / large)和形状(pill / square / icon-only)拆成正交的 mixins,才能自由组合:
@mixin button-size($height, $font-size, $padding-y, $padding-x) {
height: $height;
font-size: $font-size;
padding: $padding-y $padding-x;
}
@mixin button-shape-pill {
border-radius: 999px;
}
@mixin button-shape-square {
border-radius: 0;
}使用时:@include button-base(); @include button-size(40px, 14px, 0.3em, 1em); @include button-shape-pill;。如果把所有尺寸逻辑塞进 button-base(),每次新增一个尺寸就得改主 mixin,还容易引发参数顺序混乱——比如把 $padding-x 和 $padding-y 传反,渲染结果就错位。
导出为 CSS 自定义属性时,:root 里只放真正需要 JS 动态读取的变量
不是所有 Sass 变量都要转成 CSS custom properties。只有那些可能被 JavaScript 修改的才值得暴露,比如主题色或禁用状态透明度:
:root {
--button-bg: #007bff;
--button-disabled-opacity: 0.6;
}而像 border-radius 这种纯样式参数,留在 Sass 层用 $border-radius 更高效——CSS 变量会触发重绘,且无法参与 Sass 的数学运算(比如 calc(var(--button-height) / 2) 在圆角计算中不可靠)。另外,var(--button-bg) 在 IE 中不支持,如果还要兼容,就得 fallback 到 Sass 编译时的值。
实际项目里最常被忽略的是「组合爆炸」:button + size + shape + state + theme 五维叠加后,输出 CSS 的体积和维护成本会指数增长。与其堆砌所有变体,不如先定义 3 种核心尺寸、2 种形状、3 种状态,再按需扩展。


















