tags:

views:

340

answers:

5

This is the HTML:

<div id="testBlue">
    <span>hello</span>
    <span id="testGreen" class="testGreen">hello2</span>
</div>

If I have set in CSS:

#testBlue span { color:Blue; }    
.testGreen, #testGreen { color:Green; }

How can I override the general style in the second SPAN?

I have tried both id and class selectors but it doesnt override it.

+2  A: 
#testGreen { color: red !important;}

or

.testGreen { color: red !important;}

Either will override the inherited rule, because !important puts more weight to one side of an an otherwise equal decision.

Tomalak
Your solution worked and I upvoted it, thanks! I accepted the one given by @alexmeia because to me it feels simpler.
Dawkins
I also think his solution is nicer. You should up-vote him as well.
Tomalak
+3  A: 

Dont use important give it more weight like this

#testBlue span { color:Blue; } 
#testblue #testgreen{color:Red}

Edit

Ive been taught using !important is bad practice

Certain objects in css have different weight in the decision to apply a rule

See http://htmldog.com/guides/cssadvanced/specificity/

I suppose its not wrong to use important but better practice to use weighting for specicifity

Allen Hardy
sorry color:Green should be color:red
Allen Hardy
Well, edit your post then. Explain why !important is sub-optimal and I'll up-vote this.
Tomalak
Didnt realise I could edit
Allen Hardy
Hi, I tried this but it doesn't work
Dawkins
You still forgot to change the color to "red".
Tomalak
Now it works. +1.
Tomalak
I have tested it with IE7 and FF3 but it doesnt work
Dawkins
Yes it does, after Allen has made a small correction to his code.
Tomalak
Sorry Im erratic just having to deal with work at same time
Allen Hardy
A: 

You could use selector

#testBlue * { color:Blue; }
pbrodka
+5  A: 

In CSS, selectors with higher specificity override selectors that are more general.

In your example you defined a style for a span inside a div with id = "testBlue". This selector is more specific than the simple selector for the class or id testGreen, so it wins. You just need a selector more specific than #testBlue span, that is not difficult to find:

#testBlue span.testGreen {
    color: green;
}
alexmeia
Some elaboration as to why this works would be good. Otherwise, +1.
Tomalak
You are right. I will add some elaboration.
alexmeia
Done adding some argumentation.
alexmeia
+1  A: 

span#testGreen { color: green; }

Nakul Chaudhary