CSS 计数器意外重置“嵌套时”

妮可

我使用 css 计数器来格式化 wiki 上的一些页面(我可以在 wiki 页面中添加 CSS)。我使用计数器来编号我的标题。

这是一段工作代码:

在此处输入图片说明

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<style>
    body {
    counter-reset: h1counter;
    }
    #main-content h1 {
        width: 100%;
        background-color: #D1DEF1;
        counter-reset: h2counter;
        border-top: 1px dotted #000;
        border-bottom: 1px dotted #000;
    }
    #main-content h1:before {
        content: counter(h1counter) ".\0000a0\0000a0";
        counter-increment: h1counter;
    }
    #main-content h2 {
        width: 100%;
        background-color: #D1DEF1;
        counter-reset: h3counter;
        border-top: 1px dotted #000;
        border-bottom: 1px dotted #000;
    }
    #main-content h2:before {
        content: counter(h1counter) "." counter(h2counter) ".\0000a0\0000a0";
        counter-increment: h2counter;
    }
</style>
<body>
    <div id="main-content">
        <h1>one</h1>
        <h2>one.one</h2>
        <h2>one.two</h2>
    </div>
</body>
</html> 

但是如果我使用我的 wiki 的一些其他格式化功能(页面布局),它会以这种方式(简化)更改 html:

<body>
    <div id="main-content">
        <div class="hzlayout">
            <h1>one</h1>
            <h2>one.one</h2>
        </div>
        <div class="hzlayout">
            <h2>one.two</h2>
        </div>
    </div>
</body>

现在编号已损坏:

在此处输入图片说明

我无法弄清楚为什么 h2counter 在离开 .hzlayout div 时(或进入第二个 .hzlayout div 时)会被重置?

在此先感谢您的帮助。

阿洛奇

在一个共同的祖先建立你的柜台。使用 counter-set 而不是 counter-reset 来重新初始化您的计数器。所以:

  #main-content {
    counter-reset: h1counter h2counter h3counter;
  }
  #main-content h1 {
      width: 100%;
      background-color: #D1DEF1;
      counter-set: h2counter;
      border-top: 1px dotted #000;
      border-bottom: 1px dotted #000;
  }
  #main-content h1:before {
      content: counter(h1counter) ".\0000a0\0000a0";
      counter-increment: h1counter;
  }
  #main-content h2 {
      width: 100%;
      background-color: #D1DEF1;
      counter-set: h3counter;
      border-top: 1px dotted #000;
      border-bottom: 1px dotted #000;
  }
  #main-content h2:before {
      content: counter(h1counter) "." counter(h2counter) ".\0000a0\0000a0";
      counter-increment: h2counter;
  }
  #main-content h3:before {
      content: counter(h1counter) "." counter(h2counter)  "." counter(h3counter) ".\0000a0\0000a0";
      counter-increment: h3counter;
  }
<div id="main-content">
  <div class="hzlayout">
    <h1>one</h1>
    <h2>one.one</h2>
  </div>
  <div class="hzlayout">
    <h2>one.two</h2>
  </div>
  <div class="hzlayout">
    <h1>two</h1>
    <h2>two.one</h2>
    <h3>two.one.one</h3>
    <h3>two.one.two</h3>
  </div>
  <div class="hzlayout">
    <h2>two.two</h2>
    <h2>two.three</h2>
  </div>
</div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章