为什么我的h1设置不适用于<section> </section>中的h1元素

时间:2015-02-02 16:08:53

标签: html css

我的标题和文档的另一部分中有一个h1。我被告知这种影响搜索引擎优化,但我离题了,我只是通过复制其他人的页面并尝试按照他们的方式设置样式而不查看他们的代码。

所以我的h1样式很好但是当我在节类中定位h1时样式不适用。

h1 {
  text-align: center;
  font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 1.7em;
  font-weight: 400px;
  margin: 1px auto 13px;
}

.header h1 {
  border-top: 3px double #232323;
  padding-top: 10px;
  font-family: inherit;
}
<body>
    <h1>This is a header</h1>
    <section class="header">
        <h1>This is a header</h1>  
    </section>
</body>

我的猜测是class.h1规则覆盖了h1规则。如果是这种情况,我如何将我的顶部边框应用于我的h1,同时仍然继承h1属性。

如果我谋杀任何CSS术语,请道歉。

3 个答案:

答案 0 :(得分:5)

inherit关键字指定属性应从其父元素继承其值。所以父节是节,并且节上没有字体规则。删除继承。

&#13;
&#13;
h1 {
  text-align: center;
  font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 1.7em;
  font-weight: 400;
  margin: 1px auto 13px;
}

.header h1 {
  border-top: 3px double #232323;
  padding-top: 10px;
}
&#13;
<body>
    <h1>This is a header</h1>
    <section class="header">
        <h1>This is a header</h1>  
    </section>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您的代码似乎没有太大问题。实际上,如果您声明全局h1属性,它们将用于您网站上的所有h1。

如果您创建特定规则,那么这些规则将适用于符合该规则的任何h1,但其他属性将被继承(如果它们不同)。

我在这里更新了小提琴:http://jsfiddle.net/lharby/ukhua6jm/2/

示例:

h1 {
   /* global porperties */
   text-align: center;
   font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
   font-size: 1.7em;
   font-weight: 400px;
   margin: 1px auto 13px;
}

.photography h1 {
   border-top: 3px double #232323; /* new property */
   padding-top: 10px;
   font-size: 2em; /* overwrite existing property */
}

答案 2 :(得分:0)

对要用于覆盖<section>适用于<h1>的规则的规则使用!important。

例如,如果您要将原始h1上的字体应用于section内的字体:

h1 {
  text-align: center;
  font-family: Helvetica Neue, Helvetica, Arial, sans-serif !important;
  font-size: 1.7em;
  font-weight: 400px;
  margin: 1px auto 13px;
}

演示:http://jsfiddle.net/gcj6xLL0/

相关问题