如何使用静态字符串为分层有序列表项编号添加前缀

Pet*_*uss 5 html css

我可以为每个部分设置一个常量字符串,并且需要保留嵌套OL标签的原始层次结构。我需要的东西是:

1. First section

  1.1. Some text here, and some fruits:
        1.1.1. Apples
        1.1.2. Oranges
  1.2. Some more text here...

2. Second section

  2.1. Some second text here, and some fruits:
        2.1.1. Bannanas
        2.1.2. Mangos
  2.2. Some more second text here...
Run Code Online (Sandbox Code Playgroud)

在部分编号的情况下,我可以对它进行硬编码,但所有其他需要通过自动CSS...我尝试了这个,但它没有按预期工作:样式(CSS)阻止它们HTML块,

1. First section

  1.1. Some text here, and some fruits:
        1.1.1. Apples
        1.1.2. Oranges
  1.2. Some more text here...

2. Second section

  2.1. Some second text here, and some fruits:
        2.1.1. Bannanas
        2.1.2. Mangos
  2.2. Some more second text here...
Run Code Online (Sandbox Code Playgroud)
li:not(:last-child) {
	padding-bottom: 9pt;
}
ol ol > li:first-child {
	padding-top: 9pt;
}

/* hierarchical ordering:  */
ol {
	padding-left: 12pt;	
	counter-reset: item
}
li {
  display: block
}
li:before {
  content: counters(item, ".") ". ";
  counter-increment: item
}
section > ol li::before {
	position: relative;
	left:-4pt;
}
/* hard coding section numbers to avoid risks on bad browsers */
#sec1 > ol > li::before  { content: "1." counter(item) "."; }
#sec2 > ol > li::before  { content: "2." counter(item) "."; }
#sec3 > ol > li::before  { content: "3." counter(item) "."; }
Run Code Online (Sandbox Code Playgroud)

笔记

mrm*_*wji 3

我删除了不必要的代码并将h1s更改为h2s。

您的计数器仅计算li元素。您也需要h2使用相同的计数器来计算 s 。

了解CSS 如何counter-reset创建新范围

body {
  counter-reset: item;
}
h2:before {
  counter-increment: item;
  content: counter(item) ". ";
}
ol {
  list-style-type: none;
  counter-reset: item;
}
li:before {
  counter-increment: item;
  content: counters(item, ".") ". ";
}
Run Code Online (Sandbox Code Playgroud)
<section>
  <h2>First section</h1>
    <ol>
      <li>Some text here, and some fruits:
        <ol>
          <li>Apples</li>
          <li>Oranges</li>
        </ol>
      </li>
      <li>Some more text here.</li>
    </ol>
</section>

<section>
  <h2>Second section</h1>
    <ol>
      <li>Some second text here, and some fruits:
        <ol>
          <li>Bannanas</li>
          <li>Mangos</li>
        </ol>
      </li>
      <li>Some more second text here.</li>
    </ol>
</section>
Run Code Online (Sandbox Code Playgroud)