When HTML span
has CSS font-family
, I can't force it to use parent 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
?
How can I make this work?
The reason is that in the CSS cascade, any CSS declaration in a style attribute has higher specificity than anything you can get with a CSS rule in a style element or in a linked style sheet. Therefore, the only way to override such a rule is to use !
The style font-family can be applied on all tags for text, i.e. besides the common text section like <DIV> and <SPAN>, it can also be used for tage like table rows and table cells, <TR> and <TD>.
To change font type purely with HTML, use the CSS font-family property. Set it to the value you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a paragraph, heading, button, or span tag.
Multiple variations of a font family can be declared by changing the font-weight and src property of @font-face rule.
You could select all the children elements using .parent *
and then set font-family
to 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
.
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 {
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:
font-family
(but not others like background-color
), the current value of the parent(s).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. You could set font-family: inherit !important
if you really, really want every element to take its parent font.
Word of advice, though: Only use !important
in extreme situations. You can often one-up another CSS rule's priority in a much more gentle way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With