Mixin 与继承
Mixin(混入)和继承是 Sass / SCSS 中两种实现样式复用的强大工具。Mixin 可以带参数灵活复用样式,继承则通过 @extend 复用已有选择器的规则。
1. Mixin(混入)
定义可复用的样式块,可带参数:
@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)
继承其他选择器的样式,避免重复代码:
.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>
相关内容
- 什么是 CSS? CSS(层叠样式表)是一种用来描述网页外观样式的语言。它定义了如何为HTML元素设置颜色、字体、布局等视觉效果,使网页更加美观和易于阅读。
- CSS 的作用与工作原理 介绍CSS的主要作用及其工作原理,帮助理解如何通过样式表控制网页元素的外观和布局,实现内容与表现的分离。
- CSS 的引入方式 介绍CSS的三种主要引入方式:内联样式、内部样式表和外部样式表,帮助开发者选择合适的方法应用样式。
- 基本语法结构 介绍CSS的基本语法结构,包括选择器、属性和属性值的组成方式,帮助理解如何编写有效的样式规则。
- 注释的使用方式 介绍CSS中注释的写法和作用,帮助开发者在样式代码中添加说明,提高代码可读性和维护性。
- 基本选择器 介绍CSS中最基础的三种选择器:元素选择器、类选择器和ID选择器,是学习CSS样式编写的基础。