简体   繁体   English

如何强制span在CSS中使用父字体系列

[英]How to force span to use parent font-family in CSS

When HTML span has CSS font-family , I can't force it to use parent font-family 当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> 

Why span don't use parent font-family ? 为什么span不使用parent font-family

How can I make this work? 我怎样才能做到这一点?

You could select all the children elements using .parent * and then set font-family to inherit . 您可以使用.parent *选择所有子元素,然后将font-family设置为inherit This will effectively override the child element font and force all children elements to inherit the value of whatever the closest parent element's font is. 这将有效地覆盖子元素字体并强制所有子元素继承最接近的父元素字体的值。

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

And if you only want to target the .child element, you would obviously change the selector to .parent .child . 如果你只想定位.child元素,你显然会将选择器更改为.parent .child

Depending on what you're trying to achieve, it's also worth mentioning that you can use the direct child selector, > , in order to only target direct children: .parent > * . 根据您要实现的目标,还值得一提的是,您可以使用直接子选择器> ,以便仅定位直接子项: .parent > *

 .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 priority goes something like this: CSS优先级是这样的:

  1. Rules on this element marked with !important 关于此元素的规则标有!important
  2. High to low rule scoring based on the number of ID tags, classes, etc., for rules applying to this element. 基于ID标签,类等的数量的高到低规则评分,适用于应用于此元素的规则。
  3. The browser's default user agent styles. 浏览器的默认用户代理样式。
  4. For rules that are inherited by default, like font-family (but not others like background-color ), the current value of the parent(s). 对于默认继承的规则,如font-family (但不包括其他类似background-color ),父节点的当前值。

What your child node is getting is not number 1. in that list, but 4. The !important flag is making sure that the parent has that font set, but that importance does not carry over to children. 您的子节点获取的内容不是该列表中的数字1.但是4. !important标志确保父级具有该字体集,但该重要性不会延续到子级。 You could set font-family: inherit !important if you really, really want every element to take its parent font. 你可以设置font-family: inherit !important如果真的,真的希望每个元素都采用它的父字体。

Word of advice, though: Only use !important in extreme situations. 但是建议:只在极端情况下使用!important You can often one-up another CSS rule's priority in a much more gentle way. 您可以通过更温和的方式获得另一个CSS规则的优先级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM