简体   繁体   English

是否可以在 CSS3 选择器中使用 CSS 变量?

[英]Is it possible to use CSS vars in CSS3 selectors?

I'm trying some experiments with CSS vars, and I couldn't get this to work or find any documentation about it.我正在尝试使用 CSS 变量进行一些实验,但无法使其正常工作或找不到任何有关它的文档。 Does anyone know if it's possible to use a CSS var in a CSS3 selector?有谁知道是否可以在 CSS3 选择器中使用 CSS var?

I made the following example to explain what I'm trying to do.我做了下面的例子来解释我想要做什么。 This example is Chrome only.此示例仅适用于 Chrome。

JSFIDDLE JSFIDDLE

http://jsfiddle.net/68Rrn/ http://jsfiddle.net/68Rrn/

CSS CSS

:root {
    -webkit-var-count: 5; /* define my var! */
}

li {
    width:100px;
    height:100px;
    background-color:blue;
    display:inline-block;
    list-style:none;
}


ul li:nth-child(4) {
    background-color:red;
}

ul li:nth-child(-webkit-var(count)) { /* I can't get this working, is it even supported? I'm trying to target the 5th element with my var. */
    background-color:black;
}

HTML HTML

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

Cascading variables (ie the var() notation) aren't defined for use with anything but property declarations, so no, they cannot be used in selectors.级联变量(即var()表示法)没有定义用于除属性声明之外的任何东西,所以不,它们不能在选择器中使用。 Judging by their name, this makes sense, since only property declarations can cascade, not selectors.从它们的名字来看,这是有道理的,因为只有属性声明可以级联,而不是选择器。 From the spec :规范

A variable can be used in place of any part of a value in any property on an element.变量可用于代替元素上任何属性中值的任何部分。 Variables can not be used as property names, selectors, or anything else besides property values.变量不能用作属性名称、选择器或除属性值之外的任何其他内容。 (Doing so usually produces invalid syntax, or else a value whose meaning has no connection to the variable.) (这样做通常会产生无效的语法,或者其含义与变量没有联系的值。)

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

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