Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style body element in Material UI

I can't find any way to target root elements with the ThemeProvider from Material UI.

const theme = createMuiTheme({
  palette: {
    background: {
      default: "#00000",
      backgroundColor : 'black',
      backgroundImage: 'url(/bg.jpg)',
      backgroundPosition: 'center',
      height:'100%'
    },
    primary: {
      light: '#757ce8',
      main: '#fff',
      dark: '#002884',
      contrastText: 'grey',
    },
  },
});

1 Answers

Material UI v5

You can change the body styles by overriding MuiCssBaseline styles in createTheme():

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

const theme = createTheme({
  components: {
    MuiCssBaseline: {
      styleOverrides: {
        body: {
          ...darkScrollbar(),
          color: "darkred",
          backgroundColor: "grey",
          "& h1": {
            color: "black"
          }
        }
      }
    }
  }
});

export default function GlobalCssOverride() {
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Content />
    </ThemeProvider>
  );
}

Edit GlobalCssOverride Material Demo (forked)

Material UI v4

You can apply the styles to the body using @global class like this:

const useGlobalStyles = makeStyles({
  "@global": {
    body: {
      backgroundColor: "tomato"
    }
  }
});
const theme = createMuiTheme({});

function MyThemeProvider({ children }) {
  useGlobalStyles();
  return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
}

function App() {
  return (
    <MyThemeProvider>
      <Button variant="contained" color="primary">
        Button
      </Button>
    </MyThemeProvider>
  );
}

If you create the project by create-react-app, you can also use css/scss module to style any element globally:

/* styles.css */
body {
  color: white;
  font-size: 15px;
}
import React from "react";
import Button from "@material-ui/core/Button";
import "./styles.css";

function App() {
  return (
    <Button variant="contained" color="primary">
      Hello World
    </Button>
  );
}

Live Demo

Edit 64705335/how-to-style-body-element-in-materialui

like image 171
NearHuscarl Avatar answered Jan 23 '26 10:01

NearHuscarl