:nth-child()セレクタの一歩進んだ使い方
例えばある要素を横に3つ並べたい時、nth-child()
を使って3番目の要素だけに特定の値を指定するのはよくある手法です。
img{
mrgint-rignt: 20px;
}
img:nth-child(3){
margin-right: 0;
}
これをひとつひとつ指定するのではなく、要素の数に応じて定義したスタイルが指定される方法が、Abusing CSS3's nth-child selector to invent new ones | grackで紹介されてたのでざっと試してみました。
:nth-of-m-child
子要素がm個の時にn番目を選択するセレクタを便宜上:nth-of-m-childと呼ぶ。
例えば子要素が5の時の3番目の要素を選択したい時は
li:nth-child(3):nth-last-child(3)
と記述する。
これは
:nth-child(n):nth-last-child(m+1-n)
で求めることができる。
:family-of-m
子要素がm個の時にその子要素全てを選択するセレクタを便宜上:family-of-mと呼ぶ。
これを実現するには
E ~ F
の兄弟セレクタと先ほどの
:nth-of-m-child
を組み合わせる。
span:nth-child(1):nth-last-child(5) ~ span { ... }
上記は子要素が5つの2番目から5番目までのspan要素全てが選択される。
1番目のspan要素も選択するために下記のように修正する。
span:nth-child(1):nth-last-child(5), span:nth-child(1):nth-last-child(5) ~ span { ... }
DEMO
これらのセレクタを活用して子要素の数の異なる要素に効率よくスタイルを指定していきます。
子要素が5、8個の場合は最初の2つは横2つに並べて以降は3つ並べます。
子要素が6、9個の場合は横3つに並べて以降は3つ並べます。
子要素が7、10個の場合は最初の4つは横2つ並べて以降は3つ並べます。
このようにパターン分けしてからスタイルを定義していきます。
/*最後の要素はmrgin-rightを0にする*/ img:nth-last-of-type(1) { margin-right: 0 !important; } /* 1 */ img:only-child { max-width: 100%; } /* 2 */ img:first-child:nth-last-child(2) ~ img, img:first-child:nth-last-child(2) { max-width: 49.5%; margin-right: 1%; } /* 3 */ img:first-child:nth-last-child(3) ~ img, img:first-child:nth-last-child(3) { max-width: 32.6%; margin-right: 1%; } /* 4 */ img:first-child:nth-last-child(4) ~ img, img:first-child:nth-last-child(4) { max-width: 24.25%; margin-right: 1%; } /*5,8...のパターン*/ /* 最初の2つの要素のスタイル定義 (全てを定義して2つ目以降は上書きする) (98% / 2) */ img:first-child:nth-last-child(3n+5) ~ img, img:first-child:nth-last-child(3n+5) { max-width: 49.5%; margin-right: 1%; } /* 2つの目以降の要素のスタイル定義 (98% / 3) */ img:first-child:nth-last-child(3n+5) + img ~ img { max-width: 32.6%; margin-right: 1%; } /* 2,5,8番目はmargin-rightを0に */ img:first-child:nth-last-child(3n+5) ~ img:nth-child(3n+2) { margin-right: 0; } /*6,9...のパターン*/ /* 全ての要素のスタイル定義 (98% / 3) */ img:first-child:nth-last-child(3n+6) ~ img, img:first-child:nth-last-child(3n+6) { max-width: 32.6%; margin-right: 1%; } /* 3の倍数番目はmargin-rightを0に */ img:first-child:nth-last-child(3n+6) ~ img:nth-child(3n) { margin-right: 0; } /*7,10...のパターン*/ /* 最初の4つの要素のスタイル定義 (全てを定義して4つ目以降は上書きする) (98% / 2) */ img:first-child:nth-last-child(3n+7) ~ img, img:first-child:nth-last-child(3n+7) { max-width: 49.5%; margin-right: 1%; } /* 4つの目以降の要素のスタイル定義 (98% / 3) */ img:first-child:nth-last-child(3n+7) + img + img + img ~ img { max-width: 32.6%; margin-right: 1%; } /* 2,4,7,10番目はmargin-rightを0に */ img:first-child:nth-last-child(3n+7) + img, img:first-child:nth-last-child(3n+7) ~ img:nth-child(3n+4) { margin-right: 0; }
Comment
コメント(0)
コメントはまだありません。
コメントする
Trackback(0)