个性化阅读
专注于IT技术分析

CSS计数器counter

点击下载

本文概述

CSS计数器类似于变量。这些由CSS维护, 并且这些值可以由CSS规则递增以跟踪使用它们的次数。

CSS计数器有助于基于CSS的简单递增和显示生成内容的数字。

CSS计数器属性

以下是与CSS计数器一起使用的属性的列表:

  • counter-reset:用于创建或重置计数器。
  • counter-increment:用于增加计数器值。
  • content:用于插入生成的内容。
  • counter()或counters()函数:用于将计数器的值添加到元素。

注意:在使用CSS计数器之前, 必须使用counter-reset创建它。

CSS计数器示例

让我们举个例子, 为页面创建一个计数器, 并为每个下一个元素增加计数器的值。

请参阅以下示例:

<!DOCTYPE html>
<html>	
<head>
<style>
body {
    counter-reset: section;
}
h2::before {
    counter-increment: section;
    content: "Section " counter(section) ": ";
}
</style>
</head>
<body>
<h1>Example of CSS Counters:</h1>
<h2>Java Tutorial</h2>
<h2>HTML Tutorial</h2>
<h2>CSS Tutorial</h2>
<h2>Oracle Tutorial</h2>
<p><strong>Note:</strong> IE8 supports these properties only if a !DOCTYPE is specified.</p>
</body>
</html>

注意:在上面的示例中, 你可以看到在主体选择器中为该页面创建了一个计数器, 该计数器为每个<h2>元素增加了计数器值, 并在每个元素的开头添加了“ Section <计数器的值>:”。 <h2>元素。


CSS嵌套计数器

你也可以在计数器内创建计数器。这称为计数器嵌套。让我们以一个示例来演示嵌套计数器。

请参阅以下示例:

<!DOCTYPE html>
<html>
<head>
<style>
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) " ";
}
</style>
</head>
<body>
<h1>Java tutorials:</h1>
<h2>Core Java tutorial</h2>
<h2>Servlet tutorial</h2>
<h2>JSP tutorial</h2>
<h2>Spring tutorial</h2>
<h2>Hibernate tutorial</h2>

<h1>Web technology tutorials:</h1>
<h2>HTML tutorial</h2>
<h2>CSS tutorial</h2>
<h2>jQuery tutorial</h2>
<h2>Bootstrap tutorial</h2>

<h1>Database tutorials:</h1>
<h2>SQL tutorial</h2>
<h2>MySQL tutorial</h2>
<h2>PL/SQL tutorial</h2>
<h2>Oracle tutorial</h2>
<p><strong>Note:</strong> IE8 supports these properties only if a !DOCTYPE is specified.</p>
</body>
</html>

注意:在以上示例中, 你可以看到为该节创建了一个计数器, 并在该节中创建了另一个名为subsection的嵌套计数器。


不同级别的嵌套计数器

你可以使用嵌套计数器创建轮廓列表。它有助于你在不同级别的嵌套计数器之间插入字符串。

请参阅以下示例:

<!DOCTYPE html>
<html>
<head>
<style>
ol {
    counter-reset: section;
    list-style-type: none;
}

li::before {
    counter-increment: section;
    content: counters(section, ".") " ";
}
</style>
</head>
<body>
<h2>Different level of Nesting counters</h2>
<ol>
  <li>item</li>
  <li>item
    <ol>
      <li>item</li>
      <li>item</li>
      <li>item
        <ol>
          <li>item</li>
          <li>item</li>
          <li>item</li>
        </ol>
      </li>
      <li>item</li>
    </ol>
  </li>
  <li>item</li>
  <li>item</li>
</ol>
<p><b>Note:</b> IE8 supports these properties only if a !DOCTYPE is specified.</p>
</body>
</html>
赞(0)
未经允许不得转载:srcmini » CSS计数器counter

评论 抢沙发

评论前必须登录!