教程 css tutorial

Mixin 与继承

Mixin(混入)和继承是 Sass / SCSS 中两种实现样式复用的强大工具。Mixin 可以带参数灵活复用样式,继承则通过 @extend 复用已有选择器的规则。


1. Mixin(混入)

定义可复用的样式块,可带参数:

scss
@mixin box-shadow($x, $y, $blur, $color) {
  box-shadow: $x $y $blur $color;
}

.card {
  @include box-shadow(2px, 2px, 6px, rgba(0, 0, 0, 0.3));
  padding: 20px;
  border-radius: 8px;
}

2. 继承(@extend)

继承其他选择器的样式,避免重复代码:

scss
.button {
  padding: 10px 20px;
  background-color: #3498db;
  color: #fff;
  border-radius: 4px;
}

.btn-primary {
  @extend .button;
  background-color: #e74c3c;
}

Mixin 与继承示例

在线代码演示
源码
<!DOCTYPE html>
<html lang="zh-CN">

<head> <meta charset="UTF-8" /> <title>Sass Mixin 与继承示例</title> <style> .button { padding: 10px 20px; background-color: #3498db; color: white; border-radius: 4px; font-family: Arial, sans-serif; border: none; cursor: pointer; margin-right: 10px; }

.btn-primary {
  background-color: #e74c3c;
}

.card {
  margin-bottom: 1rem;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.3);
  width: 300px;
  margin-top: 20px;
  font-family: Arial, sans-serif;
}

</style> </head>

<body> <button class="button">默认按钮</button> <button class="button btn-primary">主按钮</button>

<div class="card"> 这是一个带阴影的卡片,使用了 Mixin 定义的阴影样式。 </div> </body>

</html>