变量
我们可以将表达式赋值给变量,并在整个样式表中使用它们:
stylus
font-size = 14px
body
font font-size Arial, sans-serif
//编译为:
body {
font: 14px Arial, sans-serif;
}
font-size = 14px
body
font font-size Arial, sans-serif
//编译为:
body {
font: 14px Arial, sans-serif;
}
变量甚至可以包含表达式列表:
stylus
font-size = 14px
font-stack = "Lucida Grande", Arial, sans-serif
body
font font-size font-stack
//编译为:
body {
font: 14px "Lucida Grande", Arial, sans-serif;
}
font-size = 14px
font-stack = "Lucida Grande", Arial, sans-serif
body
font font-size font-stack
//编译为:
body {
font: 14px "Lucida Grande", Arial, sans-serif;
}
标识符(变量名、函数等)也可以包含 $
字符。例如:
stylus
$font-size = 14px
body {
font: $font-size sans-serif;
}
$font-size = 14px
body {
font: $font-size sans-serif;
}
我们不能使用 null 创建空变量,但可以使用括号 ()
来实现:
stylus
empty = ()
body {
font: empty sans-serif;
}
empty = ()
body {
font: empty sans-serif;
}
编译为:
css
body {
font: sans-serif;
}
body {
font: sans-serif;
}
属性查找
Stylus 独有的另一个很酷的功能是能够引用_无需_将其值分配给变量的属性。一个很好的例子是垂直和水平居中元素所需的逻辑(通常使用百分比和负边距来完成,如下所示):
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
,我们可以简单地在属性名前添加 @
字符来访问该值:
stylus
#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)
另一个用例是基于其他属性的存在性在混合器中有条件地定义属性。在下面的例子中,我们应用默认的 z-index
值为 1
,但_仅当_ z-index
之前未指定时:
stylus
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
:
stylus
body
color: red
ul
li
color: blue
a
background-color: @color
body
color: red
ul
li
color: blue
a
background-color: @color