【问题标题】:How to force span to use parent font-family in CSS如何强制跨度在 CSS 中使用父字体系列
【发布时间】:2015-12-03 14:40:55
【问题描述】:

当 HTML span 有 CSS font-family 时,我不能强制它使用父 font-family

.Parent {
  font-family: tahoma !important;
}

.Child {
  font-family: cursive, geneva;
}
<div class="Parent">
  <span class="Child">Text</span>
</div>

为什么span 不使用父font-family

我怎样才能做到这一点?

【问题讨论】:

  • 从父级中删除 !important。

标签: html css font-family


【解决方案1】:

您可以使用.parent * 选择所有子元素,然后将font-family 设置为inherit。这将有效地覆盖子元素字体并强制所有子元素继承最近父元素字体的值。

.parent {
  font-family: tahoma;
}
.child {
  font-family: cursive, geneva;
}
.parent * {
  font-family: inherit;
}
<div class="parent">
  <span class="child">Text</span>
</div>

如果您只想定位.child 元素,您显然会将选择器更改为.parent .child

根据您要实现的目标,还值得一提的是,您可以使用直接子选择器&gt;,以便仅定位直接子选择器:.parent &gt; *

.parent {
  font-family: tahoma;
}
.descendant {
  font-family: cursive, geneva;
}
.parent > * {
  font-family: inherit;
}
<div class="parent">
  <span class="descendant">Direct child. <em class="descendant">Not a direct child</em></span>
</div>

【讨论】:

  • 你确定?我的意思是,如果我们用相同的选择器重新定义 CSS 中的属性,它不会被最新的值覆盖。但是关于用另一个选择器重新定义一个属性,比如'parent *',它会在我们有直接类选择器'.child'时生效吗
  • 应在未安装 tahoma 的系统上运行的示例,并显示父类内部和外部子级之间的差异:jsfiddle.net/vmzzx1a4/4
  • 另请注意,此修复不适用于通过 style 属性直接设置字体的元素,至少在我的浏览器 (Chrome 54.0.2840.59) 中不起作用。 !important 将允许覆盖内联样式:stackoverflow.com/questions/16813220/…
【解决方案2】:

CSS 优先级如下所示:

  1. 此元素上标有 !important 的规则
  2. 适用于该元素的规则根据 ID 标签、类等的数量从高到低进行评分。
  3. 浏览器的默认用户代理样式。
  4. 对于默认继承的规则,例如font-family(但不是其他类似background-color),父级的当前值。

您的子节点得到的不是该列表中的数字 1.,而是 4. !important 标志确保父节点设置了该字体,但这种重要性不会延续到孩子身上。如果您真的非常希望每个元素都采用其父字体,则可以设置 font-family: inherit !important

忠告:仅在极端情况下使用!important。您通常可以用一种更温和的方式来提升另一个 CSS 规则的优先级。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 2019-11-14
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    相关资源
    最近更新 更多