使用CSS计数器创建带有计数器重置的子部分

时间:2016-05-02 17:22:46

标签: html css css-counter

我试图让CSS计数器增加指示子项的项目。也许是因为HTML没有嵌套,重置看起来并不像我期望的那样工作。谁能帮我理解为什么?如果我重置了正文选择器中的sub-item计数器,则所有子项都会像项目一样被处理,忽略第二次重置。

CSS定义:

body {
  counter-reset: panel item;
  font-family: monospace;
}

div.panel-heading:before {
  counter-increment: panel;
  content: "Panel " counter(panel, upper-roman) ". ";
}

div.panel-body div.item:before {
  counter-increment: item;
  content: "Item " counter(item) ". ";
  counter-reset: sub-item;
}

div.panel-body div.sub-item:before {
  counter-increment: sub-item;
  content: "sub-item " counter(item) counter(sub-item, lower-alpha) ". ";
}

HTML正文:

<div class="panel">
  <div class="panel-heading">
    &lt;- should be I </div>
  <div class="panel-body">
    <div class="item">
      &lt;- should be 1
    </div>
    <div class="sub-item">
      &lt;- should be 1a
    </div>
    <div class="sub-item">
      &lt;- should be 1b
    </div>
    <div class="sub-item">
      &lt;- should be 1c
    </div>
    <div class="item">
      &lt;- should be 2
    </div>
    <div class="sub-item">
      &lt;- should be 2a
    </div>
    <div class="sub-item">
      &lt;- should be 2b
    </div>
  </div>
</div>
<div class="panel">
  <div class="panel-heading">
    &lt;- should be II </div>
  <div class="panel-body">
    <div class="item">
      &lt;- should be 3
    </div>
    <div class="sub-item">
      &lt;- should be 3a
    </div>
    <div class="item">
      &lt;- should be 4
    </div>
    <div class="sub-item">
      &lt;- should be 4a
    </div>
    <div class="sub-item">
      &lt;- should be 4b
    </div>
    <div class="sub-item">
      &lt;- should be 4c
    </div>
  </div>
</div>

为方便起见,此处为jsfiddle

1 个答案:

答案 0 :(得分:0)

好的,我明白了。我在网上发现了一些帖子,建议在伪选择器中重置不起作用。我把它们移出来了,它现在按预期工作了。但是,这似乎不会影响增量。

div.panel-body > div.item {
  counter-increment: item;
  counter-reset: sub-item;
}

div.panel-body > div.item:before {
  content: "Item " counter(item) ". ";
}

这是工作解决方案fiddle