Access HTML attribute value in SASS
是否可以在SASS中访问HTML属性值?
我有一行代码说
1 | <ul id="my_id" data-count="3"> |
其中
或者,是否可以计算某个父元素的子元素数量? 说我有这段代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <ul id="my_id" data-count="3"> <li> First list item </li> <li> Second list item </li> <li> Third list item </li> </ul> |
(您可能已经猜到了,
任何想法将不胜感激。
Sass只是CSS生成器。它实际上并没有与HTML交互,因此您不能将HTML属性用作Sass变量。
但是,CSS可以基于属性进行选择。因此,它可能会比您希望的更长,但您可以执行以下操作
1 2 | ul[data-count="3"]:after content:"There were three items in that list!" |
我想如果您只想限制自己使用最新浏览器的子集,可以将CSS
?老实说,我不知道哪个浏览器的哪个版本已完全实现此目的。我很确定Firefox拥有它,尽管我没有使用过它,并且我对其他浏览器一无所知。无论如何,它肯定没有得到很好的支持。
似乎您正在尝试获取CSS中无序列表中的项目数量(也许根据同级对象的数量来更改其大小?)。
确实,您不能将数据属性用作Sass变量。但是,给定父项中的项目数,有一种纯粹的CSS方法可以应用条件样式。另外,它很容易用Sass编写。
假设您列表中的最大项数为10,并且您要根据列表中存在的li标签数来计算li标签的大小。
1 2 3 4 5 6 | @for $i from 1 through 10 { li:first-child:nth-last-child(#{$i}), li:first-child:nth-last-child(#{$i}) ~ li { width: (100%/$i); } } |
这将输出以下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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | li:first-child:nth-last-child(1), li:first-child:nth-last-child(1) ~ li { width: 100%; } li:first-child:nth-last-child(2), li:first-child:nth-last-child(2) ~ li { width: 50%; } li:first-child:nth-last-child(3), li:first-child:nth-last-child(3) ~ li { width: 33.33333%; } li:first-child:nth-last-child(4), li:first-child:nth-last-child(4) ~ li { width: 25%; } li:first-child:nth-last-child(5), li:first-child:nth-last-child(5) ~ li { width: 20%; } li:first-child:nth-last-child(6), li:first-child:nth-last-child(6) ~ li { width: 16.66667%; } li:first-child:nth-last-child(7), li:first-child:nth-last-child(7) ~ li { width: 14.28571%; } li:first-child:nth-last-child(8), li:first-child:nth-last-child(8) ~ li { width: 12.5%; } li:first-child:nth-last-child(9), li:first-child:nth-last-child(9) ~ li { width: 11.11111%; } li:first-child:nth-last-child(10), li:first-child:nth-last-child(10) ~ li { width: 10%; } |
基本上,这使li标签的宽度为:
-
100.0% 当只有一个li标签时 -
50.00% 当有2个li标签时 -
33.33% 当有3个li标签时 -
25.00% 当有4个li标签时 -
20.00% 当有5个li标签时 -
16.66% 当有6个li标签时 -
14.28% 当有7个li标签时 -
12.50% 当有8个li标签时 -
11.11% 当有9个li标签时 -
10.00% 当有10个li标签时
有关实时示例,请参考我使用相同技巧进行的演示。希望对您有所帮助。