search
HomeWeb Front-endHTML TutorialFun times with CSS counters_html/css_WEB-ITnose

CSS counters are one of those "oh cool, didn't know CSS could do this" type of fun features. In short, CSS allows you to continuously increase a certain amount without the need for JavaScript.

Simple Counter

We start with this simple pagination example:

The numbers you see are not hardcoded In HTML, they are generated by the following CSS:

1

2

3

4

5

6

7

8

9

10

11

body {

counter-reset : pages; // initialize counter

}

a {

counter- increment : pages; // increment counter

}

a::before {

content : counter (pages); // display counter

}

Count properties follow the rules of "document appearance order". First encounter the Body element and initialize a counter called pages. Then when an a element is encountered, the pages counter is incremented and displayed.

Multiple Counters

You can have multiple counters with different names. This example has two counters with overlapping counting ranges, sections and boxes:

Related CSS:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

body {

counter-reset : sections boxes;

}

section {

counter-increment : sections;

}

section::before {

content : 'Section ' counter (sections);

}

.box {

counter-increment : boxes;

}

.box::before {

content : counter (boxes, upper-roman );

}

Here you can see the syntax for initializing multiple counters at once (line 2). For a twist, the boxes counter is displayed as upper-roman (Line 18). All parameter options of display are the same as list-style-type attribute, here is the documentation.

Stats user choices

Now we do something fun. Count attributes can be placed in pseudo-class selectors like :checked (Translator's Note: The original text is pseudo-selectors, but it is usually written as pseudo-classes selectors, so it is translated as pseudo-class selectors as usual). This allows the counter to reflect the user's selection via the checkbox. The following example counts how many items the user has selected.

The CSS is just a slight modification from the previous example. The only difference is that we increment it in the pseudo-class selector (input:checked) and only display it in a dedicated .total element.

1

2

3

4

5

6

7

8

9

10

11

body {

counter-reset : characters;

}

input:checked {

counter-increment : characters;

}

.total::after {

content : counter (characters);

}

Control increment The quantity

does not have to increase by 1. You can add any amount you want. They can even have negative growth. Building on the previous example, this one sets a special increment for each selector.

The syntax is simple enough.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

body {

counter-reset : sum;

}

#a:checked { counter-increment : sum 64 ; }

#b:checked { counter-increment : sum 16 ; }

#c:checked { counter-increment : sum -32 ; }

#d:checked { counter-increment : sum 128; }

#e:checked { counter-increment : sum 4; }

#f:checked { counter-increment : sum -8 ; }

.sum::before {

content : '= ' counter (sum);

}

Back to the topic, you can also control the initial value of the counter.

1

2

3

body {

counter-reset : kittens 41 ; // starting out with 41 kittens

}

Potential Gotcha

Display:none elements will not trigger counting. If you want to hide an element but still trigger the count, you have to hide it in another way. Here's one way:

1

2

3

4

input {

position : absolute ;

left : -9999px ;

}

Maybe you have noticed, This is exactly what I did in the last two examples. To demonstrate the effect, I've hidden the current checkboxes, but still need them to be counted when selected.

Conclusion

Great, browsers support CSS counting. Good luck~

CSS counters are amazing, but don’t forget our old friends

    and
  1. . It's still nice to order them in a basic list. CSS counters are the way to go, especially since they work on any element, giving you more flexibility both syntactically and semantically.

    Update: I should mention accessibility. CSS counting relies on generated content within pseudo-class elements. Some screen readers will read it, some won't. Therefore, it is best not to rely on pseudo-class elements for critical content. Although the CSS counters in the examples are well designed, I would not use them unchanged in a production environment.

    Fun times with CSS counters

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software