How to add padding and margin to all Material-UI components?

rostamiani picture rostamiani · Sep 1, 2018 · Viewed 51.9k times · Source

I need to add padding or margin to some of Material-UI components, but could not find an easy way to do it. Can I add these properties to all components? something like this:

<Button color="default" padding={10} margin={5}>

I know that this is possible using pure CSS and classes but I want to do it the Material-UI way.

Answer

Sakhi Mansoor picture Sakhi Mansoor · Sep 1, 2018

Material-UI's styling solution uses JSS at its core. It's a high performance JS to CSS compiler which works at runtime and server-side.

import { withStyles} from '@material-ui/core/styles';

const styles = theme => ({
  buttonPadding: {    
    padding: '30px',   
  },
});

function MyButtonComponent(props) {
  const { classes } = props;

  return (      
      <Button
        variant="contained"
        color="primary"
        className={classes.buttonPadding}
      >
        My Button
      </Button>
  );
}

export default withStyles(styles)(MyButtonComponent);

You can inject styles with withStyle HOC into your component. This is how it works and it's very much optimized.

EDITED: To apply styles across all components you need to use createMuiTheme and wrap your component with MuiThemeprovider

const theme = createMuiTheme({
  overrides: {
    MuiButton: {
      root: {
        margin: "10px",
        padding: "10px"
      }
    }
  }
});

 <MuiThemeProvider theme={theme}>
  <Button variant="contained" color="primary">
    Custom CSS
  </Button>

  <Button variant="contained" color="primary">
    MuiThemeProvider
  </Button>

  <Button variant="contained" color="primary">
    Bootstrap
  </Button>
</MuiThemeProvider>