變數
我們可以將表達式指定給變數,並在我們的樣式表中使用它們
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