为什么我的 <br> 标签被 CSS 计数器忽略了?

Why are my <br> tags ignored by CSS counters?

在下面的代码中,似乎所有 <br/> 标签都被 CSS 计数器忽略了。这是什么原因?

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      counter-reset: ele;
    }
    *::after {
      counter-increment: ele;
      content: "element count " counter(ele);
    }
  </style>
</head>

<body>

  <h1> h1 </h1>
  <h2> h2 </h2>
  <h2> h2 </h2>
  <h2> h2 </h2>

  <p><b> b </b> p</p>

  <br/>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/>

</body>

</html>

另外,元素78代表什么?

问题的解释

It looks like all the <br/> tags getting ignored by CSS counters. The reason is?

<br> 标签,与其他 'empty' 元素一样,do support counters, but unfortunately, they don't have an ::after pseudo-element。就像 <input> 元素一样,您不能使用此技巧通过 CSS 生成内容。由于在您的代码段中的 ::after pseudo-element 中增加了计数器,因此 <br> 元素的计数器不会增加,因为 br::after 根本不存在。

In the above snippet, what are elements 7 and 8 representing?"

BODY 和 HTML 标签。由于您使用 ::after,计数器会递增,内容会插入到这些元素的末尾,在其他页面内容之后。

一半修复:计算元素而不是 pseudo-elements

您可以稍微更改 CSS 以增加元素本身的计数器,并且只显示 pseudo-element 中的值。

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      counter-reset: ele;
    }
    * {
      counter-increment: ele;
    }
    *::after {
      content: "element count " counter(ele);
    }
  </style>
</head>

<body>

  <h1> h1 </h1>
  <h2> h2 </h2>
  <h2> h2 </h2>
  <h2> h2 </h2>

  <p><b> b </b> p</p>

  <br>
  <br>
  <br>
  <br>
  <br>
  <br>

</body>

</html>

上面的示例还不能正常工作,因为它在上升一个级别时不会增加计数器。这是因为当元素打开时计数器已经递增,关闭 HTML 和 BODY 不再递增计数器。

解决方法:计数 pseudo-element 和空元素

可能更好地修复它的方法:毕竟增加 ::after 中的计数器,但添加额外的 CSS 部分,为没有 [= 的元素增加计数器=14=] pseudo-element:

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      counter-reset: ele;
    }
    
    /* Increment the counter in the '::after' of non-empty elements. */
    *::after,
    /* And in the element itself for empty element. 
       List taken from https://developer.mozilla.org/en-US/docs/Glossary/Empty_element */
    link,track,param,area,command,col,base,meta,hr,source,img,keygen,br,wbr,colgroup,input
    {
      counter-increment: ele;
    }
    
    *::after {
      content: "element count " counter(ele);
    }
  </style>
</head>

<body>

  <h1> h1 </h1>
  <h2> h2 </h2>
  <h2> h2 </h2>
  <h2> h2 </h2>

  <p><b> b </b> p</p>

  <br>
  <br>
  <br>
  <br>
  <br>
  <br>

</body>

</html>

也许它并不适合所有情况,但无论如何你的问题似乎更学术。 无论如何,我希望这个解释至少能帮助您理解为什么在您的代码片段中那些 <br> 元素似乎根本没有计数器。