将渐变应用于 Material UI 的主题背景

Mar*_*ark 5 reactjs material-ui

我试图将 MuiTheme 的默认背景颜色设置为渐变,我有以下代码:

export const theme = createMuiTheme({
  palette: {
    type: "dark",
    background: {
      default: "linear-gradient(45deg, #fe6b8b 30%, #ff8e53 90%)",
    },
  },
})
Run Code Online (Sandbox Code Playgroud)

但是我注意到,material-ui 将其设置为background-color并且不允许使用渐变。
有没有办法绕过这个并让它变得background相反?

小智 8

如果您使用的是 MUI 版本“^5.8.7”,则以下内容应该有效

import {
  createTheme
} from '@mui/material/styles';

const theme = createTheme({
  components: {
    MuiCssBaseline: {
      styleOverrides: {
        body: {
          backgroundColor: #FAACA8,
          backgroundImage: `linear-gradient(19deg, #FAACA8 0%, #DDD6F3 100%)`,
        },
      },
    },
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/@mui/material@latest/umd/material-ui.development.js"></script>
Run Code Online (Sandbox Code Playgroud)


Uch*_*cha 5

默认主题背景实际上是由CssBaseline组件应用的。overrides您可以使用对象中的属性覆盖它使用的全局默认样式theme

export const theme = createMuiTheme({
  overrides: {
    MuiCssBaseline: {
      '@global': {
         body: {
           background: 'linear-gradient(45deg, #fe6b8b 30%, #ff8e53 90%)',
           backgroundRepeat: "no-repeat",
           backgroundAttachment: "fixed",
        },
      },
    },
  },
  palette: {
    type: "dark",
  },
})
Run Code Online (Sandbox Code Playgroud)

CSS基线

全球CSS