4
2

More than 3 years have passed since last update.

html&css markerで1.1や1.1.1などの目次を作る

Last updated at Posted at 2020-05-15

最近

極鶏のラーメンが食べたいです:ramen:
ついでに言うと猪一のラーメンも食べたいです:ramen:

目次

  • 目標
  • HTML
  • CSS

目標

リストの入れ子で通常のリストだと↓階層がパッと理解しづらい。
image.png

↓こんな感じのリストを作る
image.png

HTML

今回はolで括りましたがulでも大丈夫です。
olにそれぞれfirst second thirdなどの任意のクラスをつける。

index.html
<ol class="first-layer">
    <li>1つ目の階層リスト-1</li>
    <li>1つ目の階層リスト-2</li>
    <ol class="second-layer">
      <li>2つ目の階層リスト-1</li>
      <li>2つ目の階層リスト-2</li>
      <ol class="third-layer">
        <li>3つ目の階層リスト-1</li>
      </ol>
    </ol>
    <li>1つ目の階層リスト-3</li>
    <ol class="second-layer">
      <li>2つ目の階層リスト-1</li>
      <ol class="third-layer">
        <li>3つ目の階層リスト-1</li>
        <li>3つ目の階層リスト-2</li>
      </ol>
      <li>2つ目の階層リスト-2</li>
    </ol>
  </ol>

CSS

counterとmarkerを使い、作ります。

counter-resetはolが存在する度にcounter-resetで 加算していた num を0にする。
( num=0; )

ol{
    counter-reset: num;
}

counter-incrementで num に加算していく。
リストがある度に1加算される。
( num++; num+=1; )

li{
    counter-increment: num;
}

リストの後ろに marker でリストを作成。marker の content に num の数値を出力する。
( print(num) )

li:before{
    display: marker;
    content: counter(num_f)". ";
}

以上をまとめて...

style.css
li{
    list-style-type: none;
    list-style-position: inside;
}
ol.first-layer{
    counter-reset: num_f;
}
.first-layer li{
    counter-increment: num_f;
}
.first-layer li:before{
    display: marker;
    content: counter(num_f)". ";
}
ol.second-layer{
    counter-reset: num_s;
}
.second-layer li{
    counter-increment: num_s;
}
.second-layer li:before{
    display: marker;
    content: counter(num_f)'.' counter(num_s)". ";
}
ol.third-layer{
    counter-reset: num_t;
}
.third-layer li{
    counter-increment: num_t;
}
.third-layer li:before{
    display: marker;
    content: counter(num_f)'.' counter(num_s)"." counter(num_t)'. ';
}

できました!
image.png

おまけ

n.n.n.や content の '.' を '-' に変更して、
1.0.0や1-0-0も作れます。
image.png

ol.first-layer{
    counter-reset: num_f;
    counter-reset: num_s;
    counter-reset: num_t;
}
.first-layer li:before{
    display: marker;
    content: counter(num_f)'.' counter(num_s)"." counter(num_t)'. ';
}
ol.second-layer{
    counter-reset: num_s;
    counter-reset: num_t;
}
.second-layer li:before{
    display: marker;
    content: counter(num_f)'.' counter(num_s)"." counter(num_t)'. ';
}

※変更した箇所を記載

参考

マーカー
http://www6.plala.or.jp/go_west/nextcss/reference/article/marker.htm

2020/8/7 一部表記を変更

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2