CSS class subset selector
January 30th, 2009 by Bobby WhitmanI made a cool little CSS discovery recently that I have already found to be quite powerful.
Using the class selector is done with the “.” character.
.foo { color: #ff0000; } makes any <div class=”foo” /> have red text. Likwise, .bar { font-size: 50px; } makes any <div class=”bar” /> have really really big text.
With CSS, it is possible to apply multiple classes to the same element by separating them with a space. In fact, <div class=”foo bar” /> will have really really big text that is also red in color.
But what I recently discovered is that it is possible to define a style that only applies to those elements that have all of the specified classes set. This means we can create a style that is only seen when an element has both class ‘foo’ AND class ‘bar.’
This is done like so,
.foo.bar { background-color: #ff00ff; }
Now, <div class=”foo” /> and <div class=”bar” /> will both take the background of their parent, but <div class=”foo bar” /> will have a rockin’ magenta background.
Pretty cool.
This is just a simple example. What is really going on here is that we are giving a style to a set of classes. And this style gets applied whenever that set is a subset of an element’s classes.
<div class=”a b c d e f”>Hello World.</div> (This element has a class set of {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’})
.c.b.a { color: #00cc00; } (This CSS style has a class set of {‘c’, ‘b’, ‘a’}).
Since {‘c’, ‘b’, ‘a’} ⊆ {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’}, our <div> will get this style.
Hmm, I feel a set theory post coming on.