What is the purpose of using font: inherit?

2020-02-18 03:46发布

I just wanted to know why font: inherit; is used in Cascading Style Sheets.

标签: css
7条回答
Viruses.
2楼-- · 2020-02-18 04:30

Like the other answers have said, it’s to inherit a CSS property from the parent element.

What the other answers have failed to say is why you’d need this. Because, after all, CSS properties are inherited anyway, right?

Well, no. Most are, by default (but link colour isn’t inherited from the parent element, for instance). But consider this case:

p { color: blue; }

div.important { color: red; }
<div class="important">
    <p>This is a text</p>
</div>

Now the text will be blue, not red. If we want the <p> to have its parent’s styling rather than its default styling, we have to override its CSS. We could of course repeat the property value (red) but that violates DRY (don’t repeat yourself). Instead, we inherit it:

div.important p { color: inherit; }
查看更多
登录 后发表回答