为什么我的类选择器不覆盖标记选择器?

时间:2019-01-20 12:06:50

标签: html css css-selectors

所以我已经编码了一个星期,我已经在Google上搜索了30分钟,以寻找解决方案。所以请问是否已经有人问过了。我正在尝试总结每节课后学到的内容,但是没有用!

<body> <center> h1> Module 40 </h1> </center>


<p>In this module I have learned on how to use the tag <!-- <div> ---> the purpose of this tag is to create a specific group whether it is images, headers, paragraphs, etc, which you can attribute seperate properties to so it is unaffected by tag selectors. by adding a class or ID to it. </p> <br>

<div class="p1">

 <p> Like for example this paragraph is inside a div called "p1". And I have added a specific font-size for this one compared to the previous paragraph which is affected by a <strong> tag </strong> selector instead of a <strong> class </strong> selector.
</p>

</div> 

</body>

我的CSS是这样的:

p
{
font-size: 15px;  
}

/*****class selector*****/
.p1
{
font-size: 20px;  
}

类选择器是否应覆盖标签选择器?字体大小15px应用于整个文本。如果我在第二段中添加class =“ p1”,它将起作用。但是,如果我将其添加到div中,该功能不应该工作吗?拥有div的目的不是吗?

4 个答案:

答案 0 :(得分:2)

发生这种情况是由于特殊性 Specificity (特异性)是浏览器确定哪些CSS属性值与某个元素最相关的一种方法,因此将被应用。特异性基于由不同种类的CSS selectors组成的匹配规则。 您可以在这里找到最有用的文档之一-

https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

答案 1 :(得分:1)

必须为.p1 p

p
{
font-size: 15px;  
}

/*****class selector*****/
.p1 p
{
font-size: 20px;  
}
<p>In this module I have learned on how to use the tag <!-- <div> ---> the purpose of this tag is to create a specific group whether it is images, headers, paragraphs, etc, which you can attribute seperate properties to so it is unaffected by tag selectors. by adding a class or ID to it. </p> <br>

<div class="p1">

 <p> Like for example this paragraph is inside a div called "p1". And I have added a specific font-size for this one compared to the previous paragraph which is affected by a <strong> tag </strong> selector instead of a <strong> class </strong> selector.
</p>

</div> 

答案 2 :(得分:0)

否,因为您的段落是.p1的子项

所有子代都继承其父代的样式(font-size:20px),但有能力覆盖它(您可以通过将段落样式设置为font-size:15px来做到这一点)

您可以在此处阅读有关CSS继承的更多信息: https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Cascade_and_inheritance

答案 3 :(得分:0)

您的<p>标记是<div>标记的子标记,这就是为什么它不起作用的原因。尝试将类添加到<p>标签

相关问题