Css посчитать количество элементов

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

Erisan Olasheni

How to Automatically Number Elements with CSS Counters

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:

  1. Initialize the counter on the parent div using counter-reset
  2. Increment the counter value by 1 on the child div p using counter-increment
  3. Add the counter variables before the div p content using the :before pseudo selector.

The Result

s_76F886E1B187D46E2BEDCBADBD0CB5649AD0A3F515F1D7BB79358C4B37E1BADB_1592225271319_CSS_Counters_Elements_Numbering_CSS_Do_It_Yourself_Lyty_dev

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

Оцените статью