1

我正在 codeschool.com 上学习 CSS 课程,但我对特定代码感到困惑。我应该编辑代码来测试 CSS 的特定功能,我得到了正确的答案,但我不明白为什么代码实际上可以工作。这是html:

<!doctype html>
<html lang="en">
  <head>
    <title>Sven's Snowshoe Emporium</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <section id="home" class="content home group">
      <aside>
        <p>Did you know that Sven's Snowshoe Emporium produces the highest quality snowshoes                        in North America? <a href="#">Find out more</a>.</p>
      </aside>
      <article>
        <h3>New Fall Styles</h3>
        <p>Be the first at your resort to sport the hot new tennis-themed snow kicks, now available in the <a href="#">store</a>.</p>
        <a class="button" href="#">See all products</a>
      </article>
    </section>
  </body>
</html>

CSS是

.home a {
  color: #c09e79;
}
article .button {
  color: #fff;
}

我很困惑,因为在 html 代码中,'button' 是一个类,所以我认为它会在 CSS 中被标识为#button,而不是 .button

4

6 回答 6

5

单词前面的句号表示它是一个类,哈希标记表示它是一个 id。

通常,Id 在文档中仅使用一次,并且在 Class 中重复使用

#james{
 color:#FFF;
}
.Tom{
 color:#000;
}
.Big{
 font-size:4em;
}

第一个只能用 'id="James"' 访问,而第二个用 'class="Tom"

您可以在一个对象上有多个类,但只有一个 id,添加一个额外的类,您只需在其中放置一个空格。

class="Tom Big"
于 2013-09-02T17:41:30.837 回答
4

.home选择一个班级

#home选择一个 id

Id 在文档中使用一次,类可以多次使用。元素也可以有多个类,但只有一个 id。

在您的代码中,您有一个同时具有 idhome和 class的元素home。所以要么要么.home#home工作。

于 2013-09-02T17:44:04.207 回答
3

在 CSS 中,类由类名前的 a 标识.。ID 被标识为 bij a #。标签仅由其名称标识。

  • <a class="class_example">在 CSS 中由.class_example { ... }
  • <a id="id_example">在 CSS 中由#id_example { ... }
  • <a>在 CSS 中由a { ... }

您还可以将选择器堆叠在一起以进行特定选择:

  • <a class="class_example" id="id_example">可以通过a.class_example#id_example { ... }

请记住,在这种情况下,前三个标识符都将起作用。

于 2013-09-02T17:42:24.530 回答
1

这是标签名称、ID 和类之间的区别

div
#id
.class

http://jsfiddle.net/weissman258/Hw6gu/

于 2013-09-02T17:47:46.010 回答
0
/* all anchors (a tags) inside all elements that have class='home' will get this  */
.home a {
  color: #c09e79;
}

/* all elements with class='button' that are inside tag with name article will recieve this */
article .button {
  color: #fff;
}
于 2013-09-02T17:53:16.123 回答
0

该代码可能在某些浏览器中对您有用,因为它们被设计为即使在代码错误时也能正常工作。如果类和 id 不匹配,则该属性可能仅适用于第一次分类的项目。但是,如果一个项目具有“home”类并且它的样式是#home,那么在大多数情况下它几乎肯定会坏掉。

于 2013-09-02T17:56:55.043 回答