42

How do I select a class like class="boolean optional" ?

I have tried this:

.boolean optional {CSS}

.boolean_optional {CSS}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Rails beginner
  • 14,321
  • 35
  • 137
  • 257

5 Answers5

59

As Zepplock says, that's actually two classes in a single attribute: boolean and optional. The space is not part of a class name; it acts as the separator.

These three selectors will all match it:

.boolean
.optional
.boolean.optional

The last selector only picks up this element as it has both classes.

You never include a space when chaining class selectors, not even like this:

.boolean .optional

As that selects .optional elements that are contained within separate .boolean elements.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 3
    In IE6, `.boolean.optional` is equivalent to `.optional`, see http://stackoverflow.com/questions/3772290/css-selector-that-applies-to-elements-with-two-classes/3772305#3772305 – BoltClock Jul 30 '11 at 18:11
13

Those are not classes with spaces :) They are called multiple class selectors.

You basically just need to make sure all the class names are connected (no spaces between them) and separated with a dot.

.boolean.optional {

}
2

Spaces are not valid in class name. class="boolean optional" means the element has the classes boolean and optional, so you can match it with either .boolean, .optional, or if you want to match only objects that are both optional and boolean, with .boolean.optional.

phihag
  • 278,196
  • 72
  • 453
  • 469
2

Classes will never actually have spaces in their name. In your example, that is actually two classes; boolean and optional.

to apply style to an element that has both of those classes, the construct is

.boolean.optional {
 /* CSS */
}

However, IE6 is known to have some issues with this. See this link for more details on known quirks.

ckittel
  • 6,478
  • 3
  • 41
  • 71
1

I appreciate this was a while ago, but in case anyone's interested, something I've found handy also is, how to target/select an element within an element which has both classes... EXAMPLE

.boolean.optional > p {
    color: red;
}

Perhaps requires no explanation, but: turns 'paragraph text red' ONLY for paragraph's inside of elements where both classes exist i.e.both .boolean AND .optional