React中CSS类仅生效文本颜色,字体族不生效的原因咨询
font-family Set on the Parent Div Apply to the Child h1? Great question! Let’s break down exactly why your initial CSS didn’t affect the h1’s font family, and why adding a class directly to the h1 fixed the issue.
1. Browser Default Styles Are Overriding the Inherited Value
Every browser comes with a built-in set of styles called a user agent stylesheet that applies default formatting to HTML elements. For headings like h1, browsers typically set an explicit font-family (often a serif font like Times New Roman) along with other defaults like larger font size and bold weight.
Here’s a simplified version of that default h1 style:
h1 { font-size: 2em; font-weight: bold; font-family: serif; /* This explicit value overrides inheritance */ /* Other default margins/padding rules */ }
When you set font-family on the parent div, that value is passed down to the h1 via inheritance—but since the h1 already has its own explicit font-family from the browser’s default styles, the inherited value gets ignored.
2. Why color Worked Without a Class on the h1
Unlike font-family, most browsers don’t set an explicit color value for h1 elements by default. That means the h1 inherits the color: white from its parent div, since there’s no conflicting explicit style to override it.
3. Cleaner Fixes Beyond Adding a Separate Class
While adding a class directly to the h1 works perfectly, you can also avoid extra classes by targeting the h1 directly through its parent:
.app__navbar-name { color: white; } /* Target the h1 inside the navbar div to override defaults */ .app__navbar-name h1 { font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif; }
This approach keeps your HTML cleaner and achieves the same result by directly overriding the browser’s default h1 font-family.
To sum it up: The core issue is that the browser gives h1 an explicit font-family by default, which takes priority over any inherited value. For properties like color where there’s no default explicit style, inheritance works as expected.
内容的提问来源于stack exchange,提问作者asimtot

