[英]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优先级是这样的:
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.