How do I style Material UI Components with my own CSS?
We'll discuss the main methods of how to customize the styles of any Material UI component. Material UI's article here does a great job of explaining things but we'll try to simplify the concepts down even further.
The sx prop
The sx prop is defined by Material UI as "a shortcut for defining custom styles that has access to the theme." There is a whole article dedicated to the sx
prop here which defines the sx prop very well:
The sx prop lets you work with a superset of CSS that packages all of the style functions exposed in @mui/system. You can specify any valid CSS using this prop, as well as many theme-aware properties that are unique to MUI System.
The sx prop isn't just styling with CSS properties. It uses theme aware properties known as MUI System. Check out this article for how MUI System can help you be more productive than the typical styled-component approach: Why use MUI System.
How to style inner HTML elements in Material UI with the sx prop
To override nested styles within Material UI components, you can target CSS class names right from the sx prop. See this section. The CSS Class names all follow a standard pattern:
The styles injected into the DOM by Material UI rely on class names that all follow a standard pattern:
[hash]-Mui[Component name]-[name of the slot]
.
The styled utility
The styled
utility, as documented: "The utility can be used as a replacement for emotion's or styled-components' styled() utility". This means that, we can use styled
just like we use styled(AnyComponent)
in styled-components. We can target material-ui component names and classes within the style block. This is a great utility that can be very useful for creating shared and customized Material-UI components throughout your app.
import React from "react"; import Button from "@mui/material/Button"; import { styled } from "@mui/material/styles"; import Slider from "@mui/material/Slider"; import Box from "@mui/material/Box"; function SimpleSxExample() { return ( <Button variant="contained" sx={{ backgroundColor: "blue", p: 2, }} > Hello </Button> ); } function AdvancedSxExample() { return ( <Slider sx={{ "& .MuiSlider-thumb": { borderRadius: "1px", }, }} > Hello </Slider> ); } function SpecialSxPropsExample() { return ( <Box sx={{ bgcolor: "primary.main", height: (theme) => theme.spacing(10), p: 1, boxShadow: 3, typography: "body1", }} > Box </Box> ); } const StyledSlider = styled(Slider)` color: #20b2aa; :hover { color: #2e8b57; } & .MuiSlider-thumb { border-radius: 1px; } `; export default function App() { return ( <> <SimpleSxExample /> <AdvancedSxExample /> <StyledSlider /> <SpecialSxPropsExample /> </> ); }