变量
我们可将表达式分配给变量,并在样式表中使用它们
font-size = 14px
body
font font-size Arial, sans-serif
//Compiles to:
body {
font: 14px Arial, sans-serif;
}
font-size = 14px
body
font font-size Arial, sans-serif
//Compiles to:
body {
font: 14px Arial, sans-serif;
}
变量甚至可以包含表达式列表
font-size = 14px
font-stack = "Lucida Grande", Arial, sans-serif
body
font font-size font-stack
//Compiles to:
body {
font: 14px "Lucida Grande", Arial, sans-serif;
}
font-size = 14px
font-stack = "Lucida Grande", Arial, sans-serif
body
font font-size font-stack
//Compiles to:
body {
font: 14px "Lucida Grande", Arial, sans-serif;
}
标识符(变量名、函数等)也可以包含 $
字符。例如
$font-size = 14px
body {
font: $font-size sans-serif;
}
$font-size = 14px
body {
font: $font-size sans-serif;
}
我们不能使用 null 创建空变量,但括号 ()
可以
empty = ()
body {
font: empty sans-serif;
}
empty = ()
body {
font: empty sans-serif;
}
编译为
body {
font: sans-serif;
}
body {
font: sans-serif;
}
属性查找
Stylus 独有的另一个很酷的功能是能够引用在 不 将其值分配给变量的情况下定义的属性。一个很好的例子是垂直和水平居中元素所需的逻辑(通常使用百分比和负边距完成,如下所示)
#logo
position: absolute
top: 50%
left: 50%
width: w = 150px
height: h = 80px
margin-left: -(w / 2)
margin-top: -(h / 2)
#logo
position: absolute
top: 50%
left: 50%
width: w = 150px
height: h = 80px
margin-left: -(w / 2)
margin-top: -(h / 2)
我们无需分配变量 w
和 h
,只需在属性名前加上 @
字符即可访问该值
#logo
position: absolute
top: 50%
left: 50%
width: 150px
height: 80px
margin-left: -(@width / 2)
margin-top: -(@height / 2)
#logo
position: absolute
top: 50%
left: 50%
width: 150px
height: 80px
margin-left: -(@width / 2)
margin-top: -(@height / 2)
另一个用例是根据其他属性的存在有条件地在 mixin 中定义属性。在以下示例中,我们应用了默认 z-index
为 1
,但仅在未先前指定 z-index
的情况下
position()
position: arguments
z-index: 1 unless @z-index
#logo
z-index: 20
position: absolute
#logo2
position: absolute
position()
position: arguments
z-index: 1 unless @z-index
#logo
z-index: 20
position: absolute
#logo2
position: absolute
属性查找将“冒泡”堆栈,直到找到,或者如果无法解析属性,则返回 null
。在以下示例中,@color
将解析为 blue
body
color: red
ul
li
color: blue
a
background-color: @color
body
color: red
ul
li
color: blue
a
background-color: @color