TIL 004 CSS_Counter



🎯 CSSを使って自動的に数字を生成する方法を学びます!


カウンタを使用して、ページのタイトルなどを自動的に番号付けできます.counterは要素の使用回数を追跡し、増加させ、本質的に変数である.

1. counter


HTML

<body>
   <h3>Introduction</h3>
   <h3>Body</h3>
   <h3>Conclusion</h3>
</body>
 

番号付けする要素の親要素のcounter-reset:名前;発表する。


CSS(1)

body {
  counter-reset: section;
}

h3::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}

Result(1)

Section 1: Introduction
Section 2: Body
Section 3: Conclusion

✔conter-resetプロパティのデフォルト値は0ですが、変更できます。


CSS(2)

body {
  counter-reset: section 3;
}

h3::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}

Result(2)

Section 4: Introduction
Section 5: Body
Section 6: Conclusion

✔counter-incrementpropertyのデフォルト値は1ですが、変更できます。


CSS(3)

body {
  counter-reset: section 3;
}

h3::before {
  counter-increment: section 3;
  content: "Section " counter(section) ": ";
}

Result(3)

Section 6: Introduction
Section 9: Body
Section 12: Conclusion

2.カウンタ(オーバーラップカウンタ)

<div class="multiLevel">
  <ol>
    <li>item</li>          <!-- 1     -->
    <li>item               <!-- 2     -->
      <ol>
        <li>item</li>      <!-- 2.1   -->
        <li>item</li>      <!-- 2.2   -->
        <li>item           <!-- 2.3   -->
          <ol>
            <li>item</li>  <!-- 2.3.1 -->
            <li>item</li>  <!-- 2.3.2 -->
          </ol>
          <ol>
            <li>item</li>  <!-- 2.3.1 -->
            <li>item</li>  <!-- 2.3.2 -->
            <li>item</li>  <!-- 2.3.3 -->
          </ol>
        </li>
        <li>item</li>      <!-- 2.4   -->
      </ol>
    </li>
    <li>item</li>          <!-- 3     -->
    <li>item</li>          <!-- 4     -->
  </ol>
  <ol>
    <li>item</li>          <!-- 1     -->
    <li>item</li>          <!-- 2     -->
  </ol>
</div>

✔counter()関数を使用すると、重複する異なるレベルのカウンタ間を区切る文字を指定できます。


CSS

.multiLevel ol {
  counter-reset: section;
  list-style-type: none;
 }
 
 .multiLevel li::before {
   counter-increment: section;
   content: counters(section, ".") " ";  /* section 카운터 값을 마침표(.)로 구분해 결합하여 표시합니다. */
 }

Result

1 item
2 item
  2.1 item
  2.2 item
  2.3 item
    2.3.1 item
    2.3.2 item
    2.3.1 item
    2.3.2 item
    2.3.3 item
  2.4 item
3 item
4 item
1 item
2 item