CSS 计数器:跳过嵌套在另一个 OL 内的 OL

1 html css

ol我遇到了一个问题,我使用的 WYSIWYG 编辑器通过在父项内部ol而不是在父项内部创建新的来在列表中创建子项li,这使得我很难理解如何让计数器识别 Item 3 作为 3 而不是 4。我意识到执行此操作的正确方法是将 嵌套ol到 中,li但该编辑器只是不想这样做,而且我有一些不懂 HTML 的人使用该编辑器来制作列表。

我尝试过 .articlecontainer ol ol { counter-increment: none } 认为它会跳过对嵌套 OL 的计数,但是由于目前我无法理解的原因,它将第三个 LI 计算为 OL 的一部分,它甚至不是(我认为)的孩子。

.articlecontainer ol li {
  line-height: 24px;
  position: relative;
  display: block;
  padding: .4em .4em .4em 2em;
  margin: .5em 0;
  background: #f7f7f7;
  color: #444;
  text-decoration: none;
  border-radius: .3em;
  transition: all .3s ease-out;
}

.articlecontainer ol li:before {
  content: counter(li);
  counter-increment: li;
  position: absolute;
  left: -1.3em;
  top: 25px;
  /* was 50% */
  margin-top: -1.3em;
  height: 2em;
  background: #F7941E;
  width: 2em;
  border: .3em solid #fff;
  text-align: center;
  font-weight: bold;
  border-radius: 2em;
  transition: all .3s ease-out;
  line-height: 24px;
  -moz-background-clip: padding;
  color: white;
}

.articlecontainer ol {
  counter-reset: li;
}

.articlecontainer ol li:hover {
  background: #f7941e;
}
Run Code Online (Sandbox Code Playgroud)
<div class="articlecontainer">
  <ol>
    <li>Item 1</li>
    <li>Item 2</li>
    <ol>
      <li>Sub-item 1</li>
      <li>Sub-item 2</li>
      <li>Sub-item 3</li>
    </ol>
    <li>Item 3</li>
  </ol>
</div>
Run Code Online (Sandbox Code Playgroud)

Obs*_*Age 5

您可以做的是利用子组合器 ( >)来确保您的选择器仅针对所需元素的直接子元素。在您的情况下,您希望应用两个子组合器;一个确保元素ol是 的直接子元素.articlecontainer,另一个确保元素li是这些元素的直接子元素ol

.articlecontainer > ol > li {
    line-height: 24px;
    position: relative;
    display: block;
    padding: .4em .4em .4em 2em;
    margin: .5em 0;
    background: #f7f7f7;
    color: #444;
    text-decoration: none;
    border-radius: .3em;
    transition: all .3s ease-out;
}

.articlecontainer > ol > li:before {
    content: counter(li);
    counter-increment: li;
    position: absolute;
    left: -1.3em;
    top: 25px; /* was 50% */
    margin-top: -1.3em;
    height: 2em;
    background: #F7941E;
    width: 2em;
    border: .3em solid #fff;
    text-align: center;
    font-weight: bold;
    border-radius: 2em;
    transition: all .3s ease-out;
    line-height: 24px;
    -moz-background-clip: padding;
    color: white;
}

.articlecontainer > ol {
    counter-reset: li;
}

.articlecontainer > ol > li:hover {
    background: #f7941e;
}
Run Code Online (Sandbox Code Playgroud)
<div class="articlecontainer">
  <ol>
    <li>Item 1</li>
    <li>Item 2</li>
    <ol>
      <li>Sub-item 1</li>
      <li>Sub-item 2</li>
      <li>Sub-item 3</li>
    </ol>
    <li>Item 3</li>
  </ol>
</div>
Run Code Online (Sandbox Code Playgroud)

至于您对标记重组的评论,请注意该<ol>元素仅允许 <li>元素作为直接子元素。如果您想要有子菜单,它们必须驻留在父<li>元素内(如ol > li > ol > li)才能形成有效的标记。

希望这可以帮助!:)