it/css

CSS Counter

roroism 2024. 7. 24. 00:41

 

CSS Counter

  • CSS 이용하여  <ol> 요소처럼 자동으로 넘버링 하게 해줍니다.
  • CSS Counter는 CSS에서 유지 관리하는 "변수"로, CSS는 값을 추적하여 규칙에 따라 값을 증가시킬 수 있습니다. 

사용되는 속성

CSS 카운터는 "변수"와 같습니다. 변수 값은 CSS 규칙에 의해 증가될 수 있습니다(사용 횟수를 추적합니다).

  • counter-reset : 카운터를 생성하거나 재설정합니다.
  • counter-increment : 카운터 값을 증가시킵니다.
  • content : 생성된 콘텐츠 삽입.
  • counter()또는 counters()함수 : 카운터 값을 요소에 추가합니다.
body {
  counter-reset: section 0;
  /* counter 이름을 'section'으로 지정합니다. 초기값은 0입니다. 초기값은 생략 가능합니다. */
}

h3::before {
  counter-increment: section 1; /* section의 카운터 값을 1씩 증가시킵니다. 1은 생략 가능하고, 1이 기본값입니다.*/
  content: "Section " counter(section) ": "; /* section의 카운터 값을 표시합니다. */
}
<h3>Introduction</h3>
<h3>Body</h3>
<h3>Conclusion</h3>

 

결과

counter() 결과

중첩사용 Counters()

counters()를 사용하여 중첩가능.

counters() 함수를 사용해서 중첩된 카운터 사이를 분리하는 글자를 지정할 수 있습니다.

ol {
  counter-reset: section;
  /* ol 요소마다 이름이 section인 새 인스턴스를 생성합니다. */
  list-style-type: none;
}

li::before {
  counter-increment: section; /* 해당 인스턴스 안에서 section 카운터 값 증가 */
  content: counters(section, ".") " "; /* section 카운터 값을
                                            마침표(.)로 구분해 결합하여
                                            표시합니다. */
}
<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.4.1 -->
          <li>item</li>  <!-- 2.4.2 -->
          <li>item</li>  <!-- 2.4.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>