学习CSS:为什么这段代码有效?

时间:2013-09-02 17:39:21

标签: html css

我正在使用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

6 个答案:

答案 0 :(得分:5)

一个单词前面的一个完整停止表示它是一个类,一个散列标记表示它是一个id。

通常,Id在文档中只使用一次,而在Class中重复使用

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

第一个只能用'id =“James”'加入,而第二个用'class =“Tom”加入

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

class="Tom Big"

答案 1 :(得分:4)

.home选择一个类

#home选择一个ID

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

在您的代码中,您有一个包含ID home和类home的元素。因此,.home#home都可以。

答案 2 :(得分:3)

在CSS类中,在类名之前由.标识。 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 { ... }
  • 标识

请记住,在这种情况下,所有前三个标识符都可以使用。

答案 3 :(得分:1)

以下是Tag Name,Id和Class

之间的区别
div
#id
.class

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

答案 4 :(得分: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;
}

答案 5 :(得分:0)

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