- 子要素:1階層以上下にあるすべての要素。
- 直下:1階層下にあるすべての要素(2階層以上下の要素は含まない)。
- 隣接:同じ階層に並んでいる要素のうち、特定の要素の次にある要素。
- 後ろにある:同じ階層にある、特定の要素以降のすべての要素。
クラスなどを複数指定した状態を「結合子」と呼びます。
.bar {
.foo & {
}
}
.bar {
.foo > & {
}
}
.bar {
&.foo {
}
}
あるクラスの2つ目以降にmarginを指定したい場合などに多用します(後述する:not(:first-of-type)
でも可能)。
.foo {
& + & {
}
}
.foo {
& ~ * {
}
}
.foo {
& > * {
}
}
「x番目の要素」や「最後の要素」、「x番目以降の要素」のような比較的シンプルで使用頻度の高いセレクタです。
.foo {
&:nth-of-type(3) {
}
}
.foo {
&:nth-of-type(n+3) {
}
}
.foo {
&:nth-of-type(odd) {
}
}
.foo {
&:nth-of-type(even) {
}
}
.foo {
&:nth-of-type(3n) {
}
}
下記のセレクタで「1, 4, 7, 10」のように指定できます。
.foo {
&:nth-of-type(3n+1) {
}
}
.foo {
&:first-of-type {
}
}
.foo {
&:last-of-type {
}
}
.foo {
&:not(:first-of-type) {
}
}
.foo {
&:not(:last-of-type) {
}
}
.foo {
&:nth-of-type(-n+3) {
}
}
.foo {
&:nth-last-of-type(3) {
}
}
.foo {
&:nth-of-type(odd):last-of-type {
}
}
.foo {
& > :first-child {
}
}
.foo {
& > :last-child {
}
}
[class=""]
のようにすると正規表現のように指定できます。
.foo {
& > [class^="bar"] {
}
}
.foo {
& > [class$="bar"] {
}
}
.foo {
& > [class*="bar"] {
}
}
.foo
の属性aria-hidden
がfalse
に変更された要素
.foo {
&[aria-hidden="false"] {
}
}
.foo {
& > :not([class]) {
}
}
IDを属性セレクタで指定すると、#foo
とするよりも詳細度を低くできます。
#foo
-> 0, 1, 0, 0[id="foo"]
-> 0, 0, 1, 0[class="foo"]
-> 0, 0, 1, 0
[id="foo"] {
}
以下のようにクラス属性を連結することで少しずつ詳細度を上げることもできます。
.foo
-> 0, 0, 1, 0.foo.foo
-> 0, 0, 2, 0.foo.foo.foo
-> 0, 0, 3, 0
詳細度は4つの数値で計算されます。左からstyle属性、ID属性、(擬似)クラス属性、要素です。
左の数値から検証して数が多いほうが適応、数が同じであれば右の数値へと移ります。すべての数値が同じ場合は後から読み込まれたセレクタが適応されます。
ただし、important
が指定されているプロパティは詳細度に関係なく優先されますし、利用者がスタイルシートを指定している場合はそれが最優先で適応されます。
「Quantity Queries」というテクニックを使うと、「要素が3つ以上あったら、そのすべての要素を変更する」といったことができます。
最初のセレクタで3つ目の.bar
、2つ目のセレクタで4つ目以降の.bar
をすべて選択します。
.bar {
.foo &:nth-last-child(n+3),
.foo &:nth-last-child(n+3) ~ & {
}
}
.bar {
.foo &:nth-last-child(-n+3):first-child,
.foo &:nth-last-child(-n+3):first-child ~ & {
}
}
.bar {
.foo &:nth-last-child(n+3):nth-last-child(-n+4):first-child,
.foo &:nth-last-child(n+3):nth-last-child(-n+4):first-child ~ & {
}
}