CSS Counter(CSS 计数)可以允许我们使用css对页面中的任意元素进行计数,实现类似于有序列表的功能,灵活使用CSS Counter可以让我们在进行文档排版、页面布局时事半功倍,好的,请大家摩摩拳擦擦掌,精彩内容马上呈现。
1.操作计数
CSS计数(css counter)主要依靠两个属性来实现计数的操作。
counter-reset,将指定计数器复位
counter-increment,设定计数器的变化(增加的值)
1.1 counter-reset
[css] view plaincopy
语法:
counter-reset: [<user-ident> <integer>?]+ | none
其中,user-ident为需要复位的计数器名称
integer为计数器复位值
none 不计数,默认值
counter-reset可以只指定计数器(计数器的默认复位值为0),也可以同时指定计数器和复位值,也可以同时指定若干计数器,如下面代码所示。
[css] view plaincopy
someSelector{
/*some other code*/
counter-reset: counterA; /*计数器counterA 复位,复位值为0*/
counter-reset: counterA 6; /*计数器counterA 复位,复位值为6*/
counter-reset: counterA 4 counterB; /*计数器counterA 复位,复位值为4,计数器counterB复位,复位值为0*/
counter-reset: counterA 4 counterB 2; /*计数器counterA 复位,复位值为4,计数器counterB复位,复位值为2*/
}
1.2 counter-increment
[css] view plaincopy
语法:
counter-increment: [<user-ident> <integer>?]+ | none
其中,user-ident 为需要改变的计数器名称
integer 为计数器改变值,可以为正值也可以为负值,可以同时改变多个计数器
none 阻止计数器增加,默认值
代码示例如下。
[css] view plaincopy
someSelector{
/*some other code*/
counter-increment: counterA; /* 增加CounterA,每次加1 */
counter-increment: counterA 2; /* 计数器counterA,每次加2 */
counter-increment: counterA 2 counterB -1; /* counterA,每次加2,同时counterB每次减1*/
}
2.呈现内容
我们需要通过的::before,::after等伪对象配合content属性来呈现计数。content跟计数相关的属性值有以下几种
[css] view plaincopy
语法:
content:counter(name)
counter(name,list-style-type)
counters(name,string)
counters(name,string,list-style-type)