CSS - How to select multiple attribute values?

本小妞迷上赌 提交于 2020-12-14 22:48:02

问题


If I have multiple div tags with an attribute containing different numbered values, and I would like to select only number 1 through 10, what is the most efficient way to do this in css?

Is there anything like e.g. .div[line-number=1-10] ?


回答1:


This is not possible in the standard CSS. It is convenient to use a CSS preprocessor like SASS or LESS which allow you creating loops among many other features. An example with SASS:

$selector: '.div';
@for $i from 1 to 10 {
    $selector: $selector + '[line-number=' + $i + ']';
}

#{$selector} {
    // style
}

In pure CSS you are doomed to use this solution instead:

.div[line-number=1], .div[line-number=2], .div[line-number=3], .div[line-number=4], .div[line-number=5], .div[line-number=6], .div[line-number=7], .div[line-number=8], .div[line-number=9], .div[line-number=10] {
}



回答2:


if you have the ability to modify the line-number attribute starting with 0 (01,02,03,04...10) you can do this:

div[line-number^="0"], div[line-number="10"] {
  // css properties
}

if not see the answer from @jackBauer




回答3:


You cannot specify line-number in range (1-10).

This is not available in attribute selector - https://www.w3.org/TR/css3-selectors/#attribute-selectors.

But alternatively you can apply css on each attribute value with something like below

div[line-number="1"] {
  color: red;
}

div[line-number="10"] {
  color: green;
}
<p>Use attribute selectors</p>

<div line-number="1">one</div>
<div line-number="2">two</div>
<div line-number="10">ten</div>

Hope this will help in some way(y).



来源:https://stackoverflow.com/questions/41137880/css-how-to-select-multiple-attribute-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!