Recently I had around 5 emails, and dozens of PMs asking about how to use the same class name in CSS, but having it effect objects in different ways. I also had a few about how to use more than one class for an item...

So let's kill these questions for good.

I will start with changing how a class looks depending on the element...

Start with an example? Sure...

  1. This text is green
  2. This text is NOT green

Only one of the above are green, the other is not, yet they both have the class name

How is it done? Very simple. The first one is in a div, so all i did was make a class, and add div before it, like so:

CSS
  1. div.green { color: green; }
  2. .bold { font-weight: 900; }

Let me be clear on something that seems to confuse so many people out there. If the element name is BEFORE the class/id name, then it will apply to the element with that that class name. If the element name is aFTER the class/id name, it will effect that element INSIDE the element with that name.

Sooo... div.green { color: green; } would make this green:

HTML
  1. <div class="green">
  2.     This text is green
  3. </div>

As well as any other text inside of it...

However, .green div { color: green; } would not make that green, but it would make this green:

HTML
  1. <div class="green">
  2.     <div>
  3.         This text is green
  4.     </div>
  5. </div>

Make sense?

And finally, the much easier one...

To give something 2 classes, all you have to do is seperate them with a space, ie:

CSS
  1. div.green { color: green; }
  2. .bold { font-weight: 900; }

Using this HTML

HTML
  1. <div class="green bold">
  2.     This text is green AND bold
  3. </div>

Would make the text green and bold:

This text is green AND bold

You can not just use 2 classes like this:

HTML
  1. <div class="green" class="bold">
  2.     This text is green AND bold
  3. </div>

The simply don't work... It will only use the first class it sees like that.

And there you have it. Simple and elegant . Stop the email me now, please.