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

标签 html css css-counter

在下面的代码中,看起来所有的<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>标签,与其他“空”元素一样,do support counters ,但不幸的是,他们don't have an ::after pseudo-element .就像<input>元素,你不能使用这个技巧通过 CSS 生成内容。由于递增计数器发生在这个 ::after 中代码段中的伪元素,<br> 的计数器不会递增元素因为br::after根本不存在。

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

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

一半修复:计算元素而不是伪元素

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

<!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 不会再递增计数器。

解决方法:计算伪元素和空元素

更好地修复它的可能方法:增加 ::after 中的计数器毕竟,但是要添加一个额外的 CSS 片段来增加没有 ::after 的元素的计数器。伪元素:

<!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>元素似乎根本没有计数器。

关于html - 为什么我的 <br> 标签会被 CSS 计数器忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34607940/

相关文章:

jquery - 使用 jquery 在堆叠的 div 之间拖动水平条

javascript - 如何在包含背景的顶部放置具有宽度,高度的div?

html - css 不适用于范围输入 slider

html - CSS 内容不会包裹多个 div

Javascript,Connect style.display 和 style.transition 问题

Razor 三元表达式中的 HTML 文字

html - 建立一个字母栏

HTML CSS 实现嵌套排序的问题,包括数字、字母和罗马数字

html - :before 列表的 CSS 增量计数器

html - <h2> 的 CSS 计数器不会增加