CSS: 选择器 属性 继承

CSS: Selectors Property Inheritance

我是 css 的新手,所以我有这个问题:

有这个 html 文档:

<!DOCTYPE html>
<html>
<head>
<style>
body {
    background-color: #d0e4fe;
}

h1 {
    color: orange;
    text-align: center;
}

p {
    font-family: "Times New Roman";
    font-size: 20px;
}
</style>
</head>
<body>

<h1>My First CSS Example</h1>
<p>This is a paragraph.</p>

</body>
</html>

h1 标签中的文本 属性 继承自样式 class、h1 样式或两者?

进一步扩展 Harry 在评论中所说的,有多种方法可以使用 CSS 为元素定义 'style'。

  • 内联样式 - <h1 style="color:blue;">
  • 外部样式表
  • 内部样式表

在上述问题中,您使用的是内部样式表。这意味着您已将 <style> 标记添加到文档的头部,然后在其中添加样式。

还有几种方法可以使用这些方法中的任何一种来更改元素的样式。您可以:

  • 使用 ID 选择器 (#) 设置 object 的样式(参见示例 1)
  • 使用 Class 选择器 (.) 设置 object 的样式(参见示例 2)
  • 使用标签 (h1) 设置 object 样式(参见示例 3)

示例 1

#title { color:black; }
<h1 id ="title"> This is the title </h1> 

在此示例中,您可以使用 ID 识别 H1 标签,从而允许使用散列键设置单个 object 的样式。

示例 2

.title {color:black;} 
<h1 class="title"> This is the title </h1> 

在此示例中,您可以识别 object 中的 class 或单个 object,您还可以将 class 定义为特定标签{h1.title} 所以您确定该标题属于 h1 标签并将颜色更改为黑色。

示例 3

h1 {color:black;} 
<h1 class="title"> This is the title </h1> 

在此示例中,您可以识别所有标签并根据需要更改它们。这将获取文档中的所有 h1 标签,并使文字的颜色变为黑色,无论它是否属于 class。

总结示例:

总而言之,您可以结合所有这三种技术来更改各种 object 并将特定元素定义为特定样式。所以当你使用这些技术中的多种时 它会读取所有 只是为了操作的目的:所以 class 选择器会寻找 classes,标签选择器将查找标签等 Look at this JSFiddle

h1 {padding:20px;}
h1 .title {color:green;}
#subtitle {color:red;}

<h1 class="title"> TITLE GOES HERE </h1> 
<h1 id="subtitle"> This is a subtitle </h1>

在此示例中,它将向两个元素添加填充,但仅向具有特定选择器的元素添加颜色。

我希望这能为您解决问题。

The text property from h1 tag are inherited from the style class, from the h1 style or from both?

CSS 中没有 text 属性 - 所以上面的 none。

标题中任何 属性 的唯一位置 inherited 来自 body 元素。在 CSS 中,继承是当 属性 的值为 inherit(例如 font-style: inherit)时,它从 parent 元素复制 parent DOM。

您的样式表中唯一的选择器是 type selectors,唯一与 <h1> 匹配的选择器是 h1 选择器,因此该规则集中的规则将适用于标题。

如果你有 class selector that matched the <h1> (which would require it to be a member of that HTML class (via a class attribute), then it would overwrite any rules from the type selector since a class selector is more specific.