用css就可以实现累加效果的神器--counter
今天在做一个类似下面显示效果的活动页:
在前端骚操作越来越多的普遍趋势影响下,前面用箭头表示出的东西,我打算直接用before伪类去搞,这样不仅减少了标签的使用,对自己工作量的减少也是有少许作用的,然而具体实施是遇到一个头疼的问题就是伪类的content的值,因为content的值是要递增的,所以不知道counter之前,我想到的就是nth-child选择器和js控制,但是这两种,无论哪一个工作量都不小,而且,用js更有可能引发回流造成页面的性能影响。
好在,之前看张鑫旭《css世界》一书的时候,对counter略有映象,所以就把思路放到counter上了,经过十几分钟的时间成功实现了这个效果。下面结合官方解说(MDN),以及自己的理解说一下counter。
counter-reset
The counter-reset CSS property is used to reset CSS Counters to a given value.
就是说一个counter会由counter-reset重置,语法如下:
counter-reset:<custom-ident> <integer>
一般来讲,用到counter的地方肯定会是一个列表,或者类似列表的东西,所以重置一个counter应该选择在他们共同父级上,比如,我的dom长这样:
那初始化counter的地方肯定就是在ul上了!初始化之后,就要决定这个counter应该 在什么时候开始类增,所以就到counter-increment出场的时候了:
counter-increment
The counter-increment CSS property is used to increase the value of CSS Counters by a given value. The counter's value can be reset using the counter-reset CSS property.
更具体一点来说,这个属性就是用来改变前面counter-reset初始化之后的counter的,他决定了counter应该在什么时候增加,每次增加多少 ,想我前面那个dom结构肯定是遇到li的时候增加的。语法
counter-increment:<custom-ident> <integer>
以上引用均来自MDN。
所以可以写出以下的css:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | ul{ counter-reset : order 0 ; /*counter初始化*/ } ul li{ position : relative ; width : fit-content; margin : 0 auto 15px ; counter-increment : order 1 ; /*counter变化*/ list-style : none ; } ul li::before{ content : counter (order); /*counter的使用*/ position : absolute ; left : -40px ; top : 20px ; width : 30px ; height : 30px ; display : flex; justify- content : center ; align-items: center ; font-size : 16px ; color : #000 ; border-radius: 50% ; background : #fff ; } |
本文作者:子龙的博客
本文链接:https://www.cnblogs.com/ZiLongZiLong/p/17144922.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步