CSS: span.test or .test?
Is there any difference in:
#example .test{margin-top:10px}
And
#example span.test{margin-top:10px}
开发者_如何学Go
.test is totally unique, no any class with that name exists. I have been trying to use like
<div id="example">
<label for="name">Name</label>
<input name="name" type="text" />
<span class="test">asdfghjkl</span>
</div>
The first css won't work, while the second works fine. Just wondering why first wont work? Thanks
Edit:
I found out that in the input field (in above example), i had put float:left;
, which was causing the problem. If anyone is interested, here you can see example. If you remove float:left;
, it will work fine.
http://jsfiddle.net/CmXrX/1/
Yes, there is a difference. That difference is in specificity. If you have conflicting CSS rules -- two rules point to the same element but certain properties conflict -- the conflict will be sorted out by the rules about specificity.
Each type of selector has a certain number of "specificity points" For instance:
Selector type Points
-----------------------------
HTML selector 1
class selector 10
id selector 100
So if you had these two rules:
#example .test{margin-top:10px}
#example span.test{margin-top:20px}
the top margin would be 20px, because the second rule has a specificity of 111 (100 + 10 + 1) whereas the first has 110 (100 + 10).
My guess, therefore, is that you have a conflicting style somewhere that has 111 specificity.
There are two differences:
- The latter will only apply, if the class
test
is applied to aspan
and no other element. - (and most likly more relevant in your case) the latter has a higher specificity than the former.
You probably have an other rule with a higher specificity then the first selector but lower than the second. That means this other rule will override the first rule, but not the second.
I found out that in the input field (in above example), i had put float:left;, which was causing the problem. If anyone is interested, here you can see example. If you remove float:left;
, it will work fine. http://jsfiddle.net/CmXrX/1/
yes there is a difference :
<div id="example">
<label for="name">Name</label>
<input name="name" type="text" />
<span><div class="test">asdfghjkl</div></span>
</div>
精彩评论