Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Does anyone know if it’s possible to use a CSS var in a CSS3 selector?

I made the following example to explain what I’m trying to do. This example is Chrome only.

JSFIDDLE

http://jsfiddle.net/68Rrn/

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

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>
like image 237
koningdavid Avatar asked Jul 30 '13 16:07

koningdavid


People also ask

Can you use VAR in CSS?

The var() CSS function can be used to insert the value of a custom property (sometimes called a "CSS variable") instead of any part of a value of another property.

What are limitations of CSS selector?

There are several limitations of CSS such as: It cannot provide total control over document display and allows the contents of the page to come through whatever the browser is used. Ascending by selectors is not possible. Limitations of vertical control. No expressions as it is a text-based coding language.

Are CSS variables hoisted?

CSS variables are hoisted and they are moved on the top of the CSSOM before rendering the styles of respective HTML elements in the browser. Just like in JavaScript, CSS variables can be hoisted. This means that CSS variables can be used before they are declared.


1 Answers

Cascading variables (i.e. the var() notation) aren't defined for use with anything but property declarations, so no, they cannot be used in selectors. 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.)

like image 50
BoltClock Avatar answered Oct 21 '22 13:10

BoltClock