< address 要素を自動的にリンクする | 目次フレームを自動生成する >

December 8, 2009

CSS で章番号を生成する

Internet Explorer でも :before 疑似要素や counter 関連のプロパティが使えるようになったみたいです。具体的にどのバージョンから何がサポートされたのか調べてないですが。

counter 関連のプロパティについてはさまざまなサイトで説明されてるんですが、紹介されているサンプルをコピーペーストしても、多くの場合、最上位のカウンターがインクリメントされないことが多いです。

私の理解が間違ってないことを祈りますが、CSS2 勧告邦訳「12.5.1 カウンタの入れ子と作用範囲」を読んだ感じでは、counter-reset プロパティを呼び出すと、その要素以下でのみのスコープを持つ変数が新たに宣言されるような挙動になるようです。多くのサンプルではトップレベルのカウンタに対して counter-reset プロパティを呼び出してないため、スコープがその要素内になってしまっているのではないかと思われます。

なので、トップレベルのカウンタは body 要素のセレクタで counter-reset してやるとよいのではないかと思います。

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
    <head>
        <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8"/>
        <meta http-equiv="content-style-type" content="text/css"/>
        <title>カウンターのサンプル</title>
        <style type="text/css">/*<![CDATA[ */
        h1, h2, h3, h4 { line-height: 1.1; margin: 0.2em; }
        body { counter-reset: part; }
        h1 { counter-reset: chapter; }
        h1:before {
            content: counter(part) ". ";
            counter-increment: part;
        }
        h2 { counter-reset: section; }
        h2:before {
            content: counter(part) ". " counter(chapter) ". ";
            counter-increment: chapter;
        }
        h3 { counter-reset: subsection; }
        h3:before {
            content: counter(part) ". " counter(chapter) ". " counter(section) ". ";
            counter-increment: section;
        }
        h4:before {
            content: counter(part) ". " counter(chapter) ". " counter(section) ". " counter(subsection) ". ";
            counter-increment: subsection;
        }
        /* ]]> */</style>
    </head>
    <body>
        <h1>Hedding 1</h1>
        <h2>Hedding 2</h2>
        <h3>Hedding 3</h3>
        <h4>Hedding 4</h4>
        <h1>Hedding 1</h1>
        <h2>Hedding 2</h2>
        <h3>Hedding 3</h3>
        <h4>Hedding 4</h4>
        <h4>Hedding 4</h4>
        <h3>Hedding 3</h3>
        <h4>Hedding 4</h4>
        <h2>Hedding 2</h2>
        <h3>Hedding 3</h3>
        <h4>Hedding 4</h4>
    </body>
</html>

これを Google Chrome で表示するとこんな感じ。

サンプルを表示する

トラックバック

このエントリーにトラックバック:
http://frog.raindrop.jp/cgi-bin/mt/mt-tb.cgi/2460

コメント

コメントする

※ コメントスパム対策のため、コメント本文はおはよう、こんにちわ、こんばんわのいずれかより始めるようにしてください。

name:
email:

※ 必要ですが、表示しません。

url:
情報を保存する ?