- CSS счётчики
- Использование счётчиков
- Вложенные счётчики
- Спецификации
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- How to Automatically Number Elements with CSS Counters
- When to Use CSS Counters
- How to Use CSS Counters
- Counter Properties Explained
- Numbering Elements on a Web page
- Simple Numbering
- The Result
- Table of Contents Numbering
- The Result
- Making Dynamic Pagination
CSS счётчики
CSS счётчики, в своей сущности, переменные CSS, значения которых могут быть инкрементированы при помощи CSS для отслеживания количества их использования. Они позволяют регулировать внешний вид контента, основываясь на его местоположении в документе. CSS счётчики реализованы в CSS 2.1 (ссылка на спецификацию).
Значение счётчика сбрасывается (инициализируется) при помощи counter-reset (en-US).
counter-increment (en-US) может быть отображён на странице, используя функцию counter() или counters() в свойстве content .
Использование счётчиков
Для того, чтобы использовать CSS счётчики, сначала необходимо сбросить их значение (0 по умолчанию). Для того, чтобы отобразить значение счётчика — используйте функцию counter() . Следующий пример прибавляет в начале каждого h3 элемента «Section значение счётчика>:».
body counter-reset: section; /* Устанавливает значение счётчика, равным 0 */ > h3::before counter-increment: section; /* Инкрементирует счётчик*/ content: "Секция " counter(section) ": "; /* Отображает текущее значение счётчика */ >
h3>Вступлениеh3> h3>Основная частьh3> h3>Заключениеh3>
Вложенные счётчики
CSS счётчики могут быть очень полезны для создания нумерованных списков, потому что новая сущность CSS счётчика автоматически создаётся в дочерних элементах. Используя функцию counters(), можно вставить строку между разными уровнями вложенных счётчиков. Пример:
ol> li>itemli> li>item ol> li>itemli> li>itemli> li>item ol> li>itemli> li>itemli> ol> ol> li>itemli> li>itemli> li>itemli> ol> li> li>itemli> ol> li> li>itemli> li>itemli> ol> ol> li>itemli> li>itemli> ol>
Спецификации
Смотрите также
Found a content problem with this page?
This page was last modified on 26 мая 2023 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
How to Automatically Number Elements with CSS Counters
Erisan Olasheni
CSS counters are used to add counts to elements. The count is added by providing variables that can be initialized (using counter-reset ), and these variables can then be incremented by CSS rules.
Many developers overlook this powerful CSS feature, and that is why we are going to go over how to work with counters in this tutorial.
When to Use CSS Counters
CSS counters can be used whenever you need a counting system on your web page. Some of the best use cases are:
- Numbering complex lists
- Create dynamic pagination links
- Numbering steps in an on-boarding system.
In this tutorial, we will be talking about how to use CSS counters to make complex lists and create dynamic pagination.
How to Use CSS Counters
The CSS counting system consists of the counter-reset , counter-increment , counter() and counters() and content properties. These properties take care of everything you need to do in the CSS counting system.
Let’s look more closely at these properties so we understand how they can be used.
Counter Properties Explained
- counter-reset : Used to reset or initialize your counter. To use CSS counters you must first create one with this property.
- counter-increment : Used to increment the variable of an already initialized counter.
- counter() : This function does the magic. It’s used inside the content property, on a :before or :after pseudo selector, to add up the counts.
- counters() : Used for inherited counting, and generates the instance of a parent counter variable in the child.
- content : Used to add up the count value (strings) by manipulating content for :before and :after css selectors.
Now that we understand these CSS counter properties and values, let’s dive in to our examples.
Numbering Elements on a Web page
Numbering can be done in HTML, but CSS numbering provides dynamic and easy-to-control ways of doing the job using CSS counters. The following example will number the elements on web page with CSS.
First, we are going to set up some simple numbering that does just one-level numbering. Then we’ll move on to a more advanced example where we’ll set up a table of contents.
Simple Numbering
In this example, we’ll create a simple items counter with CSS. In your HTML, just create your items structure like this:
In the CSS we are going to do three key things:
- Initialize the counter on the parent div using counter-reset
- Increment the counter value by 1 on the child div p using counter-increment
- Add the counter variables before the div p content using the :before pseudo selector.
The Result
The above numbering was done with pure CSS. Interesting, right?
Now we are going to implement some more complex numbering which makes CSS counters worth learning. We will be numbering nested elements with the counters() function, which can be used for inherited counting. This generates the instance of a parent counter in the child.
Table of Contents Numbering
- Web Development
- HTML
- CSS
- CSS Introduction
- CSS Selectors
- CSS Animation
The Result
Now you can see the power of nesting counts with counters() . This saves you the hassle of improper nesting. To help you avoid mistakes, it inherits the counter properties of the parents, and appends the child’s counter to it.
So now that we are good with numbering elements, what next?
Making Dynamic Pagination
Making pagination with CSS counters is quite simple. Pagination is usually done with HTML, repeating the same set of elements and changing the numbers inside to create navigation to each page of a result.
A developer may choose to use something dynamic like making loops that generate the elements, or do it from the server. But today we’re going to use CSS to do this dynamically!
How? With our senior counters() function.
The same way we have been incrementing our values for the numbering above, we can also make a dynamic pagination list with (you guessed it) CSS counters.
Note: You don’t need to add numbers inside the li , and you can make as many as you want. Our CSS counters() are going to do the numbering for us.
ul < list-style-type: none; counter-reset: paginate-counter 0; >ul li < border: solid 3px #ccc; color: #36f; border: 5px; float: left; margin: 5px; padding: 8px 10px; font-size: 14px; cursor: pointer; text-align: center; >/* Setting styles for the inner text */ ul li:not(.previous):not(.next):before
What else can you do with counters? Let me hear your ideas.