css预处理器 sass 部分语法说明
以下介绍一些 sass 中常用的语法
1,@at-root
@at-root
是一种控制选择器生成的语法,它允许你在嵌套的规则块中,跳出并生成根级别的选择器。
举例1:
p {
@at-root .inner {
color: red;
}
}
/* 相当于 */
.inner {
color: red;
}
/* 编译为 */
.inner {
color: red;
}
举例2:
p {
@at-root .inner {
&.abc {
color: red;
}
}
}
/* 相当于 */
.inner {
&.abc {
color: red;
}
}
/* 编译为 */
.inner.abc {
color: red;
}
举例3:
下面这种情况,@at-root{}
是无效的,但也不报错。
p {
@at-root {
&.abc {
color: red;
}
}
}
/* 相当于 */
p {
&.abc {
color: red;
}
}
/* 编译为 */
p.abc {
color: red;
}
2,!default
!default
是一个重要的标记:
当定义一个带有 !default
标记的变量时,sass 会检查变量是否已经存在。
如果变量已经被定义(即已经有值),则 !default
不会对其进行任何操作,保留之前的值。
但是,如果变量尚未被定义(即没有值),则 !default
会将给定的值赋给变量。
举例:
$primary-color: blue;
$primary-color: red !default;
body {
background-color: $primary-color;
}
/* 编译为 */
body {
background-color: blue;
}
3,Map & map-has-key() & map-get()
-
Map
是一种键值对的数据结构,类似于 JavaScript 中的对象。
可以使用Map
存储一组相关的键值对,并通过键来访问对应的值。 -
map-has-key()
函数接受两个参数:Map
和键。
它会返回一个布尔值,表示该键是否存在于Map
中。 -
map-get()
函数接受两个参数:Map
和键。获取对应的值。
举例1:
$colors: (
red: #ff0000,
green: #00ff00,
blue: #0000ff
);
.has-red-color {
@if map-has-key($colors, red) {
color: map-get($colors, red);
} @else {
color: black;
}
}
/* 编译为 */
.has-red-color {
color: #ff0000;
}
举例2
// 定义变量
$sm: 768px !default;
$md: 992px !default;
$lg: 1200px !default;
$xl: 1920px !default;
// 定义 Map
$breakpoints: (
'xs': '(max-width: #{$sm})',
'sm': '(min-width: #{$sm})',
'md': '(min-width: #{$md})',
'lg': '(min-width: #{$lg})',
'xl': '(min-width: #{$xl})',
) !default;
// 定义 mixin
/* unquote 是一个内置的函数,用于移除字符串的引号 */
@mixin res($key, $map: $breakpoints) {
@if map-has-key($map, $key) {
@media only screen and #{unquote(map-get($map, $key))} {
@content;
}
} @else {
@warn "Undefined points: `#{$map}`";
}
}
.media-block {
@include res(xs) {
display: block;
}
}
/* 编译为 */
@media only screen and (max-width: 768px) {
.media-block {
display: block;
}
}
4,内置模块
内置模块是一些定义好的函数或 mixin,通过特定语法 sass:
引入。
举例,使用 math
模块:
@use 'sass:math';
// math.div(1, 24) = 1/24
.class {
max-width: (math.div(1/24) * 100) * 1%;
}
待续,以上。