well technically the selectors cascade, so that when you have a selector that overrides another one the variable value you set in that selector takes precedence, the cool thing being that the variable is of course not just set for its element but also the subtree under the element.
Since there are lots of ways to do this kind of thing, pseudo selectors, attr function etc. the ability to do dynamic and complex things from CSS, or with just CSS and HTML combined is pretty big, but as a general rule if you want to do this kind of thing statefully it is probably best to do it in JS - maintaining what variable values are in play on a particular element by setting it that way.