4

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.

6 Answers 6

9

.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; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

This style seems to match elements that only have class="c2" as well.
1

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

Comments

1

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.

Comments

1

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”.

Comments

0

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; }

2 Comments

But I want to match only elements that have both c1 and c2 classes. Your style will match any c1 or c2, right?
@rodbv: That is right. You want the selector .c1.c2 to match both classes.
0

You need a comma after .c1?

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.