Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS2 Selectors and Style override

Tags:

html

css

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.

like image 262
Santiago Corredoira Avatar asked Dec 02 '22 08:12

Santiago Corredoira


2 Answers

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;
}
like image 199
alexmeia Avatar answered Dec 18 '22 16:12

alexmeia


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

like image 34
Allen Hardy Avatar answered Dec 18 '22 16:12

Allen Hardy