CSS 计数器详解

时间:2019-09-16
本文章向大家介绍CSS 计数器详解,主要包括CSS 计数器详解使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在前端开发中总少不了列表项,对于列表项序号,射鸡师一般会列出个1,2,3...序号。在不了解css计数器属性之前,我一般会用精灵图,用类名来区分序列号图片。这样做尽管可以达到目的,但是很不方便,开发过程耗时较长而且维护修改起来较困难。用css counter配合伪类的content完美的解决了这个问题,这里详细介绍下css counter属性

计数器属性介绍

计数器的值通过使用counter-reset 和 counter-increment 操作,在 content 上应用 counter() 或 counters()函数来显示在页面上。

counter-reset

设置计数器的名称和起始值

Name:counter-reset
Value:  [ <custom-ident> <integer>? ]+ | none
Initial:    none
Applies to: all elements
Inherited:  no
Percentages:    n/a
Computed value: the keyword none or a list, each item an identifier paired with an integer
Canonical order:    per grammar
Animation type: by computed value type

custom-indent 计数器名字 可以同时命名多个计数器
integer 初始值 默认是0 也可以是负数

.counter{
    counter-reset:sequence; /* 计数器名称是sequence */
}
.counter{
    counter-reset:sequence 2; /* 计数器名称是sequence 且起始值是2*/
}

counter-increment

设置某个计数器每次计数的变化值。如果缺省,则使用默认变化值1

Name:   counter-increment
Value:  [ <custom-ident> <integer>? ]+ | none
Initial:    none
Applies to: all elements
Inherited:  no
Percentages:    n/a
Computed value: the keyword none or a list, each item an identifier paired with an integer
Canonical order:    per grammar
Animation type: by computed value type

custom-indent 计数器名字 可以同时命名多个计数器
integer 初始值 默认是1

counter()

这是个方法,不是属性,作用是用字符串或图片将计数器显示出来。这两个计算方法要和伪元素的 content 属性搭配使用。
用法一

content: counter(name)

counter 计算符前后可以随意加字符串来对最后的效果做拼接。可点击查看demo
用法二

content: counter(name,style)

这里的style参数支持的关键字值就是list-style-type支持的那些值。作用是,我们递增递减可以不一定是数字,还可以是英文字母,或者罗马文等。

list-style-type:disc | circle | square | decimal | lower-roman | upper-roman | lower-alpha | upper-alpha | none | armenian | cjk-ideographic | georgian | lower-greek | hebrew | hiragana | hiragana-iroha | katakana | katakana-iroha | lower-latin | upper-latin

可点击查看demo
counter()实现多层嵌套demo

counters()

作用和counter()一样,差别是counters只用于多层嵌套

counters(name,string)        
counters(name,string,style)  /*style参数与counter相同*/

其中,string参数为字符串(需要引号包围的)(必须参数),表示子序号的连接字符串。例如1.1的string就是'.', 1-1就是'-'.
counters()实现多层嵌套demo

对比counter()和counters()实现的多层嵌套
counter()实现多层嵌套时,他的层级序号是手动拼起来的
counters()的多层嵌套则是嵌套层会自动带上其父层的嵌套序号

注意点
一个元素,如果设置了counter-increment, 但是其display的属性值是none或者含有hidden属性(针对支持浏览器),则此计数值是不会增加的。而visibility:hidden以及其他声明不会有此现象。

兼容性

IE8以上都兼容,所以在列表项排序的时候可以放心大胆地使用,
可点击查看caniuse结果

参考资料

CSS counter计数器(content目录序号自动递增)详解

原文地址:https://www.cnblogs.com/jesse131/p/11529944.html