使用css计数器时防止嵌套有序列表中的零

owfi6suc  于 2023-04-13  发布在  其他
关注(0)|答案(2)|浏览(137)

我正在设计一个HTML嵌套有序列表(编号)。我试图实现与MS Word相同的布局,通常当您在编号列表项之前按Tab键时。例如:

1. Item at top
1.1.1.1. Item at middle
2. Item at bottom

现在我有下面的CSS,它为Item at middle设置了1.0.0.1。有没有办法用CSS来解决这个问题,而不改变HTML?

ol { counter-reset: itemCounter; padding-left: 0 }
ol li { list-style: none; }
ol li:not(:has(ol)):before {
    content: counters(itemCounter, ".") ". ";
    counter-increment: itemCounter;
}
<ol>
   <li>Item at top</li>
   <li>
      <ol>
         <li>
            <ol>
               <li>
                  <ol>
                     <li>Item at middle</li>
                  </ol>
               </li>
            </ol>
         </li>
      </ol>
   </li>
   <li>Item at bottom</li>
</ol>
bpsygsoo

bpsygsoo1#

这看起来像你需要的那样工作:

ol { counter-reset: itemCounter; padding-left: 0 }
ol li { list-style: none; }
ol li:not(:has(ol)):before {
    content: counters(itemCounter, ".") ". ";
    counter-increment: itemCounter;
}

ol>li:has(ol) {
  counter-increment: itemCounter 0;
}

ol>li ol li:has(ol) {
  counter-increment: itemCounter 1;
}
<ol>
   <li>Item at top</li>
   <li>
      <ol>
         <li>
            <ol>
               <li>
                  <ol>
                     <li>Item at middle</li>
                     <li>Item at middle</li>
                  </ol>
               </li>
            </ol>
         </li>
         <!-- a few li for testing 👇 -->
         <li>
            <ol>
               <li>
                  <ol>
                     <li>Item at middle</li>
                  </ol>
               </li>
               <li>
                  <ol>
                     <li>Item at middle</li>
                     <li>Item at middle</li>
                  </ol>
               </li>
            </ol>
         </li>
      </ol>
   </li>
   <li>Item at bottom</li>
</ol>
wsewodh2

wsewodh22#

通过此修改,嵌套的ol元素将以“1”而不是“0”开始,并且编号将从那里继续。

ol {
  counter-reset: itemCounter;
  padding-left: 0;
}

ol li {
  list-style: none;
}

ol li:not(:has(ol)):before {
  content: counters(itemCounter, ".") ". ";
  counter-increment: itemCounter;
}

ol ol {
  counter-reset: itemCounter 1; /* initialize counter to 1 */
  padding-left: 1.5em;
}
<ol>
   <li>Item at top</li>
   <li>
      <ol>
         <li>
            <ol>
               <li>
                  <ol>
                     <li>Item at middle</li>
                  </ol>
               </li>
            </ol>
         </li>
      </ol>
   </li>
   <li>Item at bottom</li>
</ol>

相关问题