【问题标题】:How to keep same css counter value for two elements如何为两个元素保持相同的css计数器值
【发布时间】:2021-01-28 04:29:25
【问题描述】:

我需要根据某个属性值或类为两个元素显示相同的 CSS 计数器值。 例如:

<!DOCTYPE html>
<html>
<head>
<style>
body {
  counter-reset: section;
}
h2::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}
</style>
</head>
<body>
<h1>CSS Counter</h1>
<h2>Point A</h2>
<h2>Point B</h2>
<h2 class="a">Point C</h2>
<h2>Point D</h2>
<h2>Point E</h2>
<h2 class="a">Point C</h2>
<h2>Point F</h2>
</html>
这是当前输出

是否有可能具有相同 a 类的 h2 元素在它们前面具有相同的计数,即两个点 C 在它们前面都有第 3 节。 这是所需的输出

是否可以使用 css 和 html 来实现?

【问题讨论】:

    标签: html css css-counter


    【解决方案1】:

    您可以通过重置特定类手动更改计数器:

    body {
      counter-reset: section;
    }
    
    h2::before {
      counter-increment: section;
      content: "Section " counter(section) ": ";
    }
    
    .a{ 
      color:red;
    }
    
    h2.mcount::before {
      counter-reset: section 2; 
    }
    <h1>CSS Counter</h1>
    <h2>Point A</h2>
    <h2>Point B</h2>
    <h2 class="a a">Point C</h2>
    <h2>Point D</h2>
    <h2>Point E</h2>
    <h2 class="a mcount">Point C</h2>
    <h2>Point F</h2>

    【讨论】:

    • 可以动态做吗?
    • 我希望您能回答“是否可以使用 CSS 和 HTML 实现这一目标?”的问题。我还没有尝试过如何动态使用它,但我认为如果您能够创建动态 CSS 并将样式添加到 HTML 并将类添加到 h2,那么它可能是可能的。
    猜你喜欢
    • 2011-03-01
    • 2019-05-06
    • 1970-01-01
    • 2014-05-29
    • 2020-05-24
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多