hello hello2

CSS2 selectors and style overrides

This is HTML:

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

If I installed 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 ids and class selectors, but it does not override it.

+4
source share
6 answers

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

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

 #testBlue span.testGreen { color: green; } 
+9
source

Do not use important, give it more weight, like this

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

Edit

I was taught to use! Bad practice is important.

Some objects in css have different weight in the decision to apply the rule

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

I believe that it is not wrong to use important, but best practice, to use weighting to clarify

+5
source
 #testGreen { color: red !important;} 

or

 .testGreen { color: red !important;} 

Or overrides the inherited rule, because !important adds more weight to one side of the other solution.

+3
source
 span#testGreen { color: green; } 
+1
source

You can use selector

 #testBlue * { color:Blue; } 
0
source

You can also use the standard CSS DOM selectors (so you can refuse class names) as follows:

 #testblue > span:first-child + span{} 

testblue span WHAT IS DIRECT DESCRIPTION AND && FIRST-CHILD NEXT SIBLING span

0
source

All Articles