Sass 属性嵌套
学习使用 Sass 的属性嵌套语法简化带命名空间的 CSS 属性书写。 · 难度:入门 · +15XP
属性嵌套简介
Sass 允许对具有相同命名空间(如 font, border, margin)的属性进行嵌套,减少重复书写前缀。
基本语法
.text {
font: {
family: Arial, sans-serif;
size: 16px;
weight: bold;
}
}编译为:
.text {
font-family: Arial, sans-serif;
font-size: 16px;
font-weight: bold;
}结合直接属性
可以在嵌套块中同时使用直接属性和嵌套属性。
.box {
border: 1px solid black {
left: none;
right: 2px dashed red;
}
}常见可嵌套属性
| 命名空间 | 子属性 |
|---|---|
| font | family, size, weight, style, variant |
| border | width, style, color, radius, collapse |
| margin | top, right, bottom, left |
| padding | top, right, bottom, left |
| background | color, image, repeat, position, size |
注意事项
- 属性嵌套仅适用于那些子属性用连字符连接的属性
- 不要滥用,嵌套过深反而降低可读性
练习提示
使用属性嵌套为一段文本设置 font 和 border 样式,要求包含 font-size, font-weight, border-style, border-color。