带有类的H1标记继承了h1的属性

时间:2015-11-19 08:32:04

标签: html css

最近我练习了一些CSS的基础知识,而当我选择Class Selectors时,我发现了一些令我困惑的疑问。

我已经声明了H1标签的一些样式属性,并且我还使用类声明了H1标签的一些样式属性。当我在我的网络浏览器上查看结果时,我发现我的H1标签与一个类继承了我的H1标签的一个属性。这是令人困惑的事情。具有类的标记如何继承具有相同标记但没有类的属性。如果是这样呢?如果我不想继承其他标签的属性,那我该怎么办呢?

<html>
<head>
<style>
/*styling for h1 tag.*/
h1
{
text-align:center;
color:yellow;
}
h1.class1
{
color:blue;
font-size:30px;
}
h2.class1
{
color:purple;
font-size:25px;
}
h3.class1
{
color:red;
font-size:15px;
}
</style>
<body>
<h1>C.S.S. Class Selector with different tags.</h1>
<hr>
<p>In this example you will see different level of headings with different styles but with same class.</p>
<h1 class="class1">
I am a H1 heading and I have class1 as a class.
</h1>
<h2 class="class1">
I am a H2 heading and I also have class1 as a class.
</h2>
<h3 class="class1">
I am a H3 heading and I also have class1 as a class.
</h3>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

CSS是级联的,这意味着你首先声明的是元素将继承的内容,直到另一个声明进一步声明为止。例如,

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

这样,所有<h1>的字体颜色都将为红色,并且将居中对齐。如果你给了一个特定的<h1>类,你可以通过如下方式覆盖它来覆盖上面的内容:

h1.class1 {
    text-align: right;
    color: blue;
}

这意味着类<h1>的{​​{1}}将不会居中对齐或红色,它们将右对齐且为蓝色。

如果您要从class1声明中省略text-align,那么class1作为类的h1将继承class1元素宣言,所以他们将集中统一。你必须覆盖首先声明它才能生效。

答案 1 :(得分:0)

h1仍然是一个h1标签,无论它是否有类。

如果它有一个类,那么它与没有类有点不同,所以在你的情况下,你需要像这样编写CSS,对于带有类的h1:

h1.class1
{
color:blue;
font-size:30px;
text-align:left;
}

或者,你可以写:

h1.class1
{
color:blue;
font-size:30px;
text-align:inherit;
}

要使用类创建h1,请以与其他文本相同的方式浮动。

答案 2 :(得分:0)

你必须使用h1 class =“class1”来覆盖css,因为如果你使用.h1,它将对标签中的所有h1使用相同的css。

相关问题