How can I setup some print styles using MUI 5.5.2

Viewed 485

I'm looking to add some specific print styling and I'm struggling to find any documentation on how I would do that using MUI's themeing system.

declare module '@mui/material/styles' {
    interface Theme {
      "@media print": ThemeOptions,
    }
    // allow configuration using `createTheme`
    interface ThemeOptions {
      "@media print"?: ThemeOptions;
    }
}
const theme = createTheme({
    typography: {
        h2: {
            fontSize: '2rem',
            fontWeight: 700,
            borderBottom: '2px solid black',
        },
    },
    '@media print': {
        typography: {
            h2: {
                fontSize: '8rem',
                borderBottom: '20px solid red',
                color: blue[100],
            }
        }
    },
});

In the example above I can see the changes I've made to the h2 normally but when I go to print I'm not seeing the print styles applied.

1 Answers

When MUI applies the variant-specific styles, it does it using the following line:

...(ownerState.variant && theme.typography[ownerState.variant]),

In your example with a variant of "h2", this means it will only find the styles within theme.typography.h2. No code will ever look for anything at theme['@media print']. Any media-query-specific styles need to be nested within theme.typography.h2. Below is a working example.

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

const theme = createTheme({
  typography: {
    h2: {
      fontSize: "2rem",
      fontWeight: 700,
      borderBottom: "2px solid black",
      "@media print": {
        fontSize: "8rem",
        borderBottom: "20px solid red",
        color: "blue"
      }
    }
  }
});
export default function App() {
  return (
    <ThemeProvider theme={theme}>
      <Typography variant="h2">Hello CodeSandbox</Typography>
    </ThemeProvider>
  );
}

Edit media print

Related