Search code examples
htmlcsscss-counter

how to number questions using class in CSS


I have created a list of questions and plan to add more in the future. I want to number the questions using CSS for example each question is in a section as given below.

<section class = "question">The Question</section>

Is there any way to number them automatically using the "question" class ??


Solution

  • Yes, you can with the :before pseudo-element and CSS counters:

    body {
      counter-reset: section;                   /* Set the section counter to 0 */
    }
    section.question::before {
      counter-increment: section;               /* Increment the section counter*/
      content:  counter(section) ": "; /* Display the counter */
    }
    <section class="question">The Question</section>
    <section class="question">The Question</section>
    <section class="question">The Question</section>
    <section class="question">The Question</section>

    You can read more about CSS counters at https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Counters and http://www.w3.org/TR/CSS2/generate.html#generate.html#counters