tags:

views:

45

answers:

6

This could be the silliest question I've ever made, but why does the text below is not rendered red?

<html>
  <style>
  .c1 .c2 { 
     color: red; 
  }
  </style>
  <body>
     <span class="c1 c2">This should be red</span>
  </body>
</html>

Edit: I want to match elements that contain both c1 and c2 classes, like the example above, no less.

A: 

Because .c1 .c2 selects a c2 element that is a child/descendant of a c1 element.

What you want is:

c1,
c2 {color: red; }

In response to comment from OP

To target only elements with both classes:

c1.c2 {color: red; }
David Thomas
But I want to match only elements that have both c1 and c2 classes. Your style will match any c1 or c2, right?
rodbv
Then you want `c1.c2`
David Thomas
@rodbv: That is right. You want the selector `.c1.c2` to match both classes.
Guffa
+6  A: 

.c1 .c2 matches a c2 element inside a c1 element, just like html body matches a body element inside an html element. Remove the space to match an element with both classes:

.c1.c2 { 
   color: red; 
}
John Kugelman
This style seems to match elements that only have class="c2" as well.
rodbv
@rodbv - only in IE6.
Adam Kiss
A: 

You need a comma after .c1?

egrunin
That would work to make this element red, but it seems that the intended meaning is to specify the rule for elements having *both* `c1` and `c2`, in which case it's `.c1.c2`.
Arkku
Yeah, I saw his edit. Nevermind :)
egrunin
A: 

It should be .c1.c2. The way you have it written is a c2 INSIDE a c1.

webdestroya
A: 

The selector .c1 .c2 really means an element with the class c2 inside an element with the class c1.

To get the desired result, change your selector to .c1.c2, which will match elements with both styles.

wsanville
A: 

If the intended meaning of your CSS is to match “an element with both c1 and c2 in its list of classes”, then it sould be .c1.c2. The given selector (.c1 .c2) means “an element with the class c2 that is a directly inside an element with the class c1”.

Edit: For sake of completeness, to match an element with at least one of the classes c1 and c2, you would use .c1, .c2. So, the space refers to the structure of the document, no space is “and” and comma is “or”.

Arkku