如何使 Material UI 中的主题样式覆盖页面级别的字体继承 CSS?

huangapple go评论54阅读模式
英文:

How can I make theme styles in Material UI override a page-level font inherit CSS

问题

我正在使用React+MUI编写一个浏览器扩展,该扩展将被注入到页面的DOM中。该页面包含一个带有以下规则的CSS文件:

h6 {
  font: inherit;
}

当我在我的扩展DOM中放置一个<h6>元素时,它不会加粗,尽管我明确使用Material UI主题设置了字体粗细:

export const theme = createTheme({
  typography: {
    h6: {
      fontWeight: 800
    }       
  },        
}); 

这里有一个展示问题的工作示例:https://codesandbox.io/s/frosty-waterfall-5u2q7o?file=/src/App.js

如何让主题中的规则优先于渗入我的小部件DOM的页面级CSS规则?

英文:

I'm writing a browser extension using React+MUI, which will get injected into the DOM of a page. That page contains a CSS file with a rule that does the following:

h6 {
  font: inherit;
}

When I put a &lt;h6&gt; element in my extension's DOM, it is not bolded, even though I'm explicitly setting a font weight using a Material UI theme:

export const theme = createTheme({
  typography: {
    h6: {
      fontWeight: 800
    }       
  },        
}); 

Here's a working example showing the problem: https://codesandbox.io/s/frosty-waterfall-5u2q7o?file=/src/App.js

What's the best way for getting the rules in the theme to have precedence over page-level CSS rules that bleed into my widget's DOM?

答案1

得分: 2

The theme styles don't have any global impact on h6 tags. You need to explicitly use the Typography component in order for those theme styles to have an impact.

以下是您代码的翻译部分:

import "./styles.css";

import { createTheme, ThemeProvider } from "@mui/material/styles";
import Typography from "@mui/material/Typography";

export const theme = createTheme({
  typography: {
    h6: {
      fontWeight: 800
    }
  }
});

export default function App() {
  return (
    <ThemeProvider theme={theme}>
      <div className="App">
        <Typography variant="h6">This should be bold</Typography>
      </div>
    </ThemeProvider>
  );
}

如何使 Material UI 中的主题样式覆盖页面级别的字体继承 CSS?

英文:

The theme styles don't have any global impact on h6 tags. You need to explicitly use the Typography component in order for those theme styles to have an impact.

Here's a modified version of your code:

import &quot;./styles.css&quot;;

import { createTheme, ThemeProvider } from &quot;@mui/material/styles&quot;;
import Typography from &quot;@mui/material/Typography&quot;;

export const theme = createTheme({
  typography: {
    h6: {
      fontWeight: 800
    }
  }
});

export default function App() {
  return (
    &lt;ThemeProvider theme={theme}&gt;
      &lt;div className=&quot;App&quot;&gt;
        &lt;Typography variant=&quot;h6&quot;&gt;This should be bold&lt;/Typography&gt;
      &lt;/div&gt;
    &lt;/ThemeProvider&gt;
  );
}

如何使 Material UI 中的主题样式覆盖页面级别的字体继承 CSS?

huangapple
  • 本文由 发表于 2023年6月1日 03:44:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定