之间有什么区别
tag.class
和tag .class
或
tag#id
和tag #id
?
答案 0 :(得分:3)
tag.class
将名为tag
和的所有元素与类class
匹配,例如:
div.foo { color: red; }
匹配<div class="foo">
tag .class
匹配.class
元素后代的所有tag
元素(请注意tag
和.class
之间的空格) :
中的
div .foo { color: red; }
与<span>
<div><p><span class="foo">
相匹配
tag#id
和tag #id
与上述内容类似,但id
属性上的匹配除了class
属性[1]
div#foo { color: red; }
匹配<div id="foo">
中的
div #foo { color: red; }
与<span>
<div><p><span id="foo">
相匹配
请记住,因为id=""
属性是唯一的,因此额外的选择器可能是多余的,例如div#bar
可以简化为#bar
(除非您在#bar
可能包含不同元素标记名称的不同网页上重复使用相同的CSS规则)。
[1]:在HTML中也是如此,在使用CSS的其他SGML和XML语言中,.class
和#id
选择器可以映射到其他属性名称。
答案 1 :(得分:2)
tag.class
表示tag
class='class'
。像这样:
<!-- This tag would be selected -->
<tag class="class">
...
</tag>
tag .class
表示class='class'
的元素,是<tag>
的后代。像这样:
<tag>
...
<!-- This div would be selected -->
<div class="class">
</div>
...
</tag>
通常,类似selector1 selector2
的内容意味着匹配selector2
的元素,并且是与selector1
匹配的元素的后代。考虑这个例子:
<强> CSS:强>
/*
div.face matches a div with class="face"
div.eye#left matches a div with class="eye" and id="left"
Hence, this would select an element with class="eye" and id="left" which is
inside a div with class="face"
*/
div.face div.eye#left {
}
<强> HTML:强>
<div class="face"> <!-- div.face -->
<div class="upper">
<div class="eye" id="left"></div> <!-- div.eye#left is selected -->
<div class="eye" id="right"></div>
</div>
</div>
答案 2 :(得分:1)
空格()是后代选择器,请参阅文档:http://www.w3.org/TR/CSS2/selector.html#descendant-selectors
长篇短篇tag.class
适用于tag
元素 类class
,而tag .class
适用于class
的任何元素在tag
元素内的类。