skip to Main Content

I’m looking for a way to extend MUI v5’s MuiCssBaseline with a rule to set margin: 0 on all the heading and paragraph tags. I’ve tried this:

MuiCssBaseline: {
  styleOverrides: {
    '@global': {
      h4 {
        margin: 0
      }
    }
  }
}

but it resulted in TS18004: No value exists in scope for the shorthand property 'h4'. Either declare one or provide an initializer.

What’s the right way? Should it be set in MuiCssBaseline at all?

2

Answers


  1. Chosen as BEST ANSWER

    Building upon the accepted answer this is what I came up with.

    MuiCssBaseline: {
      styleOverrides: {
        'some-prop': {
          ...
        },
        'p, h1, h2, h3, h4, h5, h6': {
          margin: 0
        }
      }
    }
    

  2. Below is an example of one syntax for how to handle this in the theme. You can find documentation about overriding global styles here: https://mui.com/material-ui/customization/how-to-customize/#4-global-css-override.

    import * as React from "react";
    import CssBaseline from "@mui/material/CssBaseline";
    import { ThemeProvider, createTheme } from "@mui/material/styles";
    
    const theme = createTheme({
      components: {
        MuiCssBaseline: {
          styleOverrides: `
            h1, h2, h3, h4, h5, h6, p {
              margin: 0;
            }
          `
        }
      }
    });
    
    export default function OverrideCssBaseline() {
      return (
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <h1>h1 element</h1>
          <h2>h2 element</h2>
          <h3>h3 element</h3>
          <h4>h4 element</h4>
          <h5>h5 element</h5>
          <h6>h6 element</h6>
          <p>p element</p>
        </ThemeProvider>
      );
    }
    

    Edit global styles

    Another approach that is not reliant on CssBaseline is to use the GlobalStyles component as show below.

    import * as React from "react";
    import GlobalStyles from "@mui/material/GlobalStyles";
    
    export default function GlobalStylesExample() {
      return (
        <>
          <GlobalStyles styles={{ "h1, h2, h3, h4, h5, h6, p": { margin: 0 } }} />
          <h1>h1 element</h1>
          <h2>h2 element</h2>
          <h3>h3 element</h3>
          <h4>h4 element</h4>
          <h5>h5 element</h5>
          <h6>h6 element</h6>
          <p>p element</p>
        </>
      );
    }
    

    Edit global styles

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search