安裝stylus
yarn add stylus
可以通過執行npx stylus style.styl可以将styl檔案轉換成同名css檔案
npx stylus -w style.styl 添加-w參數可以實時編譯
Partial Reference
可以使用^[N]來代替部分選擇選擇器。
Partial reference works similar to the parent reference, but while parent reference contains the whole selector, partial selectors contain only the first merged N levels of the nested selectors, so you could access those nesting levels individually.
局部引用跟父級引用相似,但是父級引用包含了整個選擇器,局部引用隻包含最初的比對上的N層嵌套的選擇器,是以可以擷取到逐層的選擇器。
The ^[0] would give you the selector from the first level, the ^[1] would give you the rendered selector from the second level and so on:
^[0]可以擷取到第一層選擇器,^[1]可以擷取到第二層選擇器。
例如:
.foo
&__bar
width: 10px
^[0]:hover &
width: 20px
would be rendered as
.foo__bar {
width: 10px;
}
.foo:hover .foo__bar {
width: 20px;
}
可以看出^[0]擷取的是第一層選擇器.foo,&擷取的是目前父選擇器。
下面的例子可以看到N取負數的場景:
.foo
&.bar
.l1
.l2
^[0]
width: 10px;
^[1]
width: 20px;
^[2]
width: 30px;
^[-1]
width: 40px;
npx stylus style.styl,編譯後:
.foo {
width: 10px;
}
.foo.bar {
width: 20px;
}
.foo.bar .l1 {
width: 30px;
}
.foo.bar .l1 {
width: 40px;
}
正如文檔中介紹的,N取負數值時,^[-I]可以擷取到父級選擇器&前面的第I個選擇器。
Negative values are counting from the end, so ^[-1] would give you the last selector from the chain before &:
上文中^[-1]位置的&選擇器是.foo.bar .li .l2,是以^[-1],就是.foo.bar .li。
Ranges in partial references
可以用^[N…M]表示需要選擇的選擇器的範圍區間。如果number從正數開始,則選擇的選擇器不會包括其前面的選擇器,而是你指定區間内的選擇器。原文
^[N…M] anywhere in a selector, where both N and M can be numbers, represents a partial reference.
N,和M的取值前後沒有關系,例如[-1, 1]和[1, -1]的結果是一樣的,因為stylus是從前面的選擇器開始選取。
如果N和M的值相等,則表示隻選擇N這一層選擇器。下面的例子可以說明:
需要注意的是,這種情況下-1就是指目前層的父選擇器。而不是父選擇器的前一層,這一點與^[-1]有很大差別。
.foo
&.bar
.l1
.l2
^[1..-2]
width: 10px;
^[0..2]
height: 20px;
^[1]
width: 30px;
^[1..1]
width: 40px;
.l3
.l4
&
^[-1..-1]
width: 50px;
.l5
.l6
&.l7
^[1..-1]
width: 60px;
編譯後
.bar .l1 {
width: 10px;
}
.foo.bar .l1 {
height: 20px;
}
.foo.bar {
width: 30px;
}
.bar {
width: 40px;
}
.l6.l7 {
width: 60px;
}
^[1…-2]中,1選擇的是第2個選擇器,和倒數第2個選擇器之間的選擇器,注意第2個選擇器中包含一個&父選擇器,這時候是取不到父選擇器的。
本例子中^[-1…-1]則沒有選擇到選擇器。
而^[1…-1]則選擇的是.l6.l7選擇器。
~/ 表示最初的選擇符,Initial Reference。可以當作^[0]的簡寫。
…/相對選擇符
/表示根選擇符,即不嵌套在任何選擇符下
内建函數built-in-function selector()可以傳回目前編譯的選擇符,一般用在maxin中
.foo
selector()
// => '.foo'
.foo
&:hover
selector()
// '.foo:hover'
selector()還可以接受參數,這種情況下,該函數不會預先準備作用域,即不會預設提供&符作用域。
.foo
selector('.bar')
// => '.bar'
.foo
selector('&:hover')
// '.foo:hover'
再看一組例子:
.l8
selector()
height: 20px;
上面這樣設定雖然不會編譯出錯,但是沒有任何意義,不會編譯出對應的選擇符。但是可以在selector()加上{}就可以。
.l8
{selector()}
height: 20px;
=>
.l8 .l8 {
height: 20px;
}
同理,
.l8
{selector('.l9')}
height: 20px;
=>
.l8 .l9 {
height: 20px;
}
當然,也可以給selector()傳入多個參數。
{selector('.a', '.b', '.c, .d')}
color: red
=>
.a
.b
.c,
.d
color: red
selectors() 内建函數傳回目前層的逗号分割的選擇器清單。
.a
.b
.c
&__d
content: selectors()
=>
.a .b .c__d {
content: '.a', '& .b', '& .c', '&__d';
}