实现效果
css实现:有多个宽度不同的标签水平排列,当外层宽度不足时,会自动提示超出的数量
实现思路
CSS 如何动态累计数字?
利用 CSS计数器
1 2 3 4 5 | counter-reset : num var(--num); counter-increment : num; ::after{ content : "+" counter (num); } |
CSS 如何知道哪些元素在容器之外?
CSS滚动驱动动画。这里用到的是视图进度,也就是关注的是元素自身位置,元素进入到容器范围之内就会触发动画,非常类似 JS中的Intersection Observer
1 2 3 4 5 6 7 8 9 10 | tag{ animation : appear; animation-timeline: view( inline ); animation-range: contain; } @keyframes appear{ to { background-color : #9747FF ; } } |
CSS 如何区分是否溢出(显示数量)
利用CSS滚动驱动动画,可以检测容器是否可滚动,也就是是否超出。所以我们只需要将遮罩放在滚动驱动动画里就行了,关键实现如下
1 2 3 4 5 6 7 8 9 | .con{ animation : check; animation-timeline: scroll (x self); } @keyframes check{ from,to { -webkit- mask : linear-gradient (to right , #fff calc( 100% - 30px ), transparent ); } } |
完整代码
1 2 3 4 5 6 7 8 9 10 11 | <div class= "wrap" > <div class= "con" style= "--num:7" > <a class= "tag" >HTML</a> <a class= "tag" >CSS</a> <a class= "tag" >JavaScript</a> <a class= "tag" >Flutter</a> <a class= "tag" >Vue</a> <a class= "tag" >React</a> <a class= "tag" >Svelte</a> </div> </div> |
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | html,body{ font-family : -apple-system, "BlinkMacSystemFont" , sans-serif ; margin : 0 ; height : 100% ; display : flex ; justify-content : center ; flex-direction : column; align-items : center ; background : #fff ; gap: 20px ; accent- color : #9747FF ; } . wrap { width : 300px ; display : flex ; align-items : center ; padding : 15px ; outline : 2px solid #9747FF ; gap: 5px ; overflow : hidden ; } .con{ position : relative ; display : flex ; gap: 5px ; padding : 5px ; overflow : hidden ; counter-reset : num; animation : check; animation-timeline: scroll (x self); margin-right : -46px ; } @keyframes check{ from,to { margin-right : 0 ; -webkit- mask : linear-gradient (to right , #fff calc( 100% - 30px ), transparent ); } } .wrap::after{ content : "+" counter (num); padding : . 2em . 5em ; background-color : #FFE8A3 ; color : #191919 ; border-radius : 4px ; } .tag{ padding : . 2em . 5em ; background-color : #c49ef5 ; color : #fff ; border-radius : 4px ; counter-increment : num 1 ; animation : appear; animation-timeline: view( inline ); animation-range: contain; } @keyframes appear{ from,to { background-color : #9747FF ; counter-increment : num 0 ; } } |
到此这篇关于纯 CSS 实现多标签自动显示超出数量的文章就介绍到这了,更多相关CSS 自动显示超出数量内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章,希望大家以后多多支持IT俱乐部!