如何在我的css代码中增加计数器?

时间:2017-01-09 12:39:03

标签: html css list css-tables css-counter

在我的html代码中,我定义了以下列表:

<p class="list">first.</p>
<p class="list">second.</p>

现在,在css我有:

.list {
  display: table;
}
.list:before {
  display: table-cell;
  counter-increment: counter;
  content: counter(counter) '.';
  padding-right: 5px;
}

,页面上的结果是:

1. first
1. second

如何将第二个数字增加到2的值?

5 个答案:

答案 0 :(得分:13)

您应该在counter-reset包装上使用list属性 - 请参阅下面的演示:

&#13;
&#13;
body {
 counter-reset:counter;
}
.list {
  display: table;
}
.list:before {
  display: table-cell;
  counter-increment: counter;
  content: counter(counter) '.';
  padding-right: 5px;
}
&#13;
<p class="list">first.</p>
<p class="list">second.</p>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

您可以使用:

,而不是将HTML包装在<p>标记中
<ol>
  <li>first</li>
  <li>second</li>
</ol>

这将为您提供所需的输出。

这是一个有效的fiddle.

这样你就不需要在CSS中做任何计算,更容易,更简单的解决方案和兼容的跨浏览器。

答案 2 :(得分:3)

您需要重置计数器:

body {
    counter-reset: section;
}
.list {
  display: table;
}
.list:before {
  display: table-cell;
  counter-increment: section;
  content:counter(section) ". ";
  padding-right: 5px;
}
<p class="list">first.</p>
<p class="list">second.</p>

答案 3 :(得分:1)

body {
    counter-reset: section;
}

h1 {
    counter-reset: subsection;
}

h1::before {
    counter-increment: section;
    content: "Section " counter(section) ". ";
}

h2::before {
    counter-increment: subsection;
    content: counter(section) "." counter(subsection) " ";
}
<h1>HTML tutorials:</h1>
<h2>HTML Tutorial</h2>
<h2>CSS Tutorial</h2>

<h1>Scripting tutorials:</h1>
<h2>JavaScript</h2>
<h2>VBScript</h2>

<h1>XML tutorials:</h1>
<h2>XML</h2>
<h2>XSL</h2>

来源:http://www.w3schools.com/css/css_counters.asp

答案 4 :(得分:-2)

你应该这样使用:

<ol>
    <li class="list">first.</li>
    <li class="list">second.</li>
</ol>