Result
自動連番できるCSSカウンターを親要素と子要素の入れ子で2つ使う、みたいなやつ
異なるコンテナに含まれる同一要素に自動でナンバリングします
結論から言うと、複数のカウンター名を使えるのでそのまま使えば動作します
css
body { /*sectionsとboxesの2つのカウンター名を設定して初期化*/ counter-reset : sections boxes; } /*親要素のカウンター*/ section { counter-increment : sections; } section::before { /*数字に接頭語を付与*/ content : 'その' counter (sections); } /*子要素のカウンター*/ .box { counter-increment : boxes; } .box::before { content : counter (boxes, decimal-leading-zero ); } |
counter-resetには複数のカウンター名を設定する事が出来るので異なる要素への自動ナンバリングが可能です
やっつけなので分かりにくいExampleになってしまいましたが以下のように5つのCSSカウンターを同時に使う、みたいな事も可能です
section、div、p、span、i要素にそれぞれナンバリングを施しました
いくつ要素が使われているかを数えることが出来ていると思います
html
< section > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > </ section > < section > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > </ section > < section > < div class = 'box' ></ div > < div class = 'box' ></ div > < div class = 'box' ></ div > </ section > ・ ・ ・ |
CSS以外はこれといって施す事はありません
もちろんclassを使えば、より細かな設定が出来るので「要素を数える」という目的はHTMLとCSSだけで概ね達成可能かもしれませんね
では、動的に追加された要素はどうなるでしょうか。以下に簡単なサンプルを作ってみました
動的に増やした場合
ボタンを押すとp要素が追加されます。p要素にはCSSカウンターでナンバリングしてあります
当然といえば当然ですが、動的に増えても問題なくイメージ通りに動作してくれました。これといって特別な作業をせずに済むのは楽ですね
can i use
各ブラウザのサポート状況です。非対応はIE6-7くらいですし、issuesも無さそうなので、CSSカウンターはどのブラウザでも使えるという認識で問題ないと思います