简体   繁体   English

自定义数据属性的CSS选择器?

[英]CSS selector for custom data-attribute?

Why my star is not appearing in YELLOW ? 为什么我的明星没有出现在黄色? How to fix it ? 怎么解决?

Here's the relevant code for the above issue. 以下是上述问题的相关代码。

HTML HTML

<div class="tpl" data-favorite="1">
  <div>
    <span class="favorite">★</span>
    <span class="text">Italian Pizza: salmon, olives, onion, tomato, blue-cheese</span>
  </div>
</div>

CSS CSS

[data-favorite=1] {
    background: #AAA;
    border-left: 3px solid green
}
.favorite {
    font-size: 2em;
    padding: 0 1 0 1em;
}
[data-favorite=1] .favorite {
    color:yellow;
}
[data-favorite=0] .favorite {
    color:#AAA;
}

Fiddle 小提琴

You'll want to use 你会想要使用

[data-favorite="1"] {}

The difference being the quotes "" around the value. 不同之处在于值周围的引号“”。

Here's the working jsFiddle 这是工作的jsFiddle

You need to use " around the attribute value 您需要使用"围绕属性值

[data-favorite="1"] {
   /* Styles goes here */
}

Demo 演示


Why is that so? 为什么会这样?

CSS Specification - 6.3. CSS规范 - 6.3。 Attribute selectors 属性选择器

Attribute values must be CSS identifiers [1] or strings . 属性值必须是CSS 标识符 [1]字符串 [CSS21] The case-sensitivity of attribute names and values in selectors depends on the document language. [CSS21]选择器中属性名称和值的区分大小写取决于文档语言。

Identifiers 身份标识

[1] In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); [1]在CSS中,标识符(包括选择器中的元素名称,类和ID)只能包含字符[a-zA-Z0-9]和ISO 10646字符U + 00A0及更高,加上连字符( - )和下划线(_); they cannot start with a digit , two hyphens, or a hyphen followed by a digit. 它们不能以数字 ,两个连字符或连字符后跟数字开头。 Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). 标识符还可以包含转义字符和任何ISO 10646字符作为数字代码(请参阅下一项)。 For instance, the identifier "B&W?" 例如,标识符“B&W?” may be written as "B\\&W\\?" 可以写成“B \\&W \\?” or "B\\26 W\\3F". 或“B \\ 26 W \\ 3F”。


So the issue is that the value of your attribute starts with a number, if you have something like this in your HTML (You already do) 所以问题是你的属性的值以数字开头,如果你的HTML中有这样的东西(你已经这样做了)

<span data-favorite="0">Color Me red</span>

 [data-favorite=0] { color: red;} 

WONT WORK 工作

Demo 演示


But, if you have something like 但是,如果你有类似的东西

<span data-favorite="a0">Color Me red</span>

[data-favorite=a0] { color: red;}

WILL WORK (Even without quotes) because the value of your attribute starts with an alphabet [1] . 将工作 (即使没有引号),因为属性的值以字母[1]开头。

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM