要设置代码样式:
   <div id="top-header">
        <div id="logo">
            <a href="http://example.com/>logo link</a>
        </div>
</div>
什么时候用div#logo{}
,什么时候用#logo{}?
要设置代码样式:
   <div id="top-header">
        <div id="logo">
            <a href="http://example.com/>logo link</a>
        </div>
</div>
什么时候用div#logo{}
,什么时候用#logo{}?
div#logo将仅适用于 id 为logodiv 的元素,而 just#logo将适用于 id 为 的任何元素logo。但是,鉴于您不应该在同一页面上拥有具有相同 id 的元素,因此这种特殊情况应该不会产生任何影响。
当按类而不是 id 进行样式设置时,它会更有用,例如:
<div class="top-header">
    <div class="logo">
        <a href="http://example.com/>logo link</a>
    </div>
    <span class="logo">Hello</span>
</div>
这里div.logo{}不会将样式应用到跨度。
The only time div#logo is useful is if you want to select one element, which has the id logo and is a <div>, or select no elements if such a <div> doesn't exist. This use case implies that you don't know until runtime whether #logo will be the id of a <div> or some other HTML element like a <span>.
If you just want to select the element with the id #logo, then just use #logo.
ID 意味着在包含 1000,000 个 ID 的 1000,000 个 Div 的网页中具有唯一含义,每个 Div 应具有特定 ID,但是,它们可以具有相同的类。
示例:将其视为一所有 1000 名学生的学校的教室。每个学生都有他/她自己的特定学生证,但他们都共享同一个班级。
因此,如果学生是 Divs,ID 号 (#) 567 的学生,在 css 中的评分如下:
假设这样:
     <student id="1" class="Grade_03">...</student> // as in <div id="1" class="Grade_03"></div>
    <student id="2" class="Grade_01">...</student>
    <student id="3" class="Grade_02">...</student>
    <student id="n" class="Grade_03">...</student>
    Student#567{
    Math:90%;
    English:80%;
    }
//Or:
  #567{
    Math:90%;
    English:80%;
    }
但是,如果您想向该班的所有学生讲话,假设 Grade_03:
Student.Grade_03{
TeacherName:"Mr_Smith";
}
如果您没有重复的学生证,则说Student#567或两者都将指向同一个学生。#567
既然 anid是独一无二的,#logo{ ... }那就足够了。
使用类时,可以更加灵活,例如:
CSS:
.class1 {
    color: red;
}
span.class1 {
    color: blue;
}
HTML:
<h1 class="class1">heading</h1>
<a class="class1">link</a>
<span class="class1">span</span>
在上面的示例中,标题和链接文本将为红色。然而,跨度将是蓝色的。
把它想象成“如果它恰好是一个 div,我只想选择一个带有这个 id 的元素。”。在 99% 的情况下使用id选择器就足够了,但是如果元素是动态添加的,并且您知道它将具有什么 id 但不知道它将是什么类型的元素,则必须这样做。
ID 始终是唯一的。
There is no use of adding element selector in front of an ID.
Here is the reason why you should avoid using same IDs with a page. http://jsfiddle.net/jDxS8/1/ When you try to add styles on the fly, you can't.
EDIT : I misjudged Mansfield's comment class="logo" as id sorry for that.