Can you count a particular class with CSS?

后端 未结 7 901
刺人心
刺人心 2021-02-02 08:08

Lets say I have a simple list like so:

  1. one
  2. two
  3. &l
7条回答
  •  鱼传尺愫
    2021-02-02 08:53

    This can be done with CSS-counters

    If I set display:none on the generated content with the counter, the counter skips over it, and continues to the next item!

    FIDDLE

    (Edit: Or, alternatively - as others have pointed out - we could increment the counter only on the elements with the particular class - like so)

    ol {
      counter-reset: count;
      list-style-type: none;
      padding-left: 30px;
    }
    li:before {
      content: counter(count)".";
      counter-increment: count;
    }
    li:not(.count) {
      padding-left: 13px;
    }
    li:not(.count):before {
      display: none;
    }
    1. one
    2. two
    3. three
    4. four
    5. blabla
    6. five
    7. six
    8. blabla
    9. seven

    So actually, with counters, not only can we count classes, we can also count any selector combination.

    Here's an example for proof of concept:

    html {
      counter-reset: divs;
    }
    body {
      counter-reset: paragraphs;
      position: relative;
    }
    div {
      counter-increment: divs;
    }
    .wpr {
      counter-reset: count-me;
      position: relative;
    }
    .container {
      position: relative;
      border-bottom: 1px solid green;
    }
    .container .count-me {
      counter-increment: count-me;
    }
    .container p {
      counter-increment: paragraphs;
    }
    .wpr:after {
      content: "Number of count-me classes in container:" counter(count-me);
      position: absolute;
      bottom: -20px;
    }
    .container:after {
      content: "Number of paragraphs:" counter(paragraphs);
      position: absolute;
      bottom: -40px;
    }
    body:after {
      content: "Number of divs:" counter(divs);
      position: absolute;
      bottom: -60px;
    }
    div1
    div2
    div3 count-me
    div4 count-me

    I"m a paragragh

    div5

    I"m a paragragh

    div6 count-me
    div7 count-me

    I"m a paragragh

    div8

提交回复
热议问题