Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Theming and Customization

The sx Prop and styled()

Style Material UI components with the sx prop and the styled() API: theme-aware values, responsive objects, pseudo-selectors, nested rules and when to use each.

Material UI gives you two main tools for adding your own styles: the sx prop for one-off styling right where you use a component, and styled() for reusable styled components. Both are built on Emotion, both read the theme, and both support media queries, pseudo-classes and nested selectors. Knowing which to use, and what each costs, keeps your code short and your pages quick.

Material UI is not loadable in the live editors here, so the real MUI snippets are read-only. The runnable examples are stand-ins: a small sx interpreter and a styled helper that follow the same rules, written for this lesson.

The sx prop

Almost every MUI component accepts sx. It takes an object (or a function returning one, or an array) of CSS properties, and it adds theme-aware shortcuts.

JSX
// Real Material UI, read-only
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';

<Box
  sx={{
    p: 2,                       // padding: theme.spacing(2) = 16px
    mx: 'auto',                 // margin-left and margin-right: auto
    maxWidth: 480,              // numbers become px for most properties
    bgcolor: 'primary.main',    // theme.palette.primary.main
    color: 'primary.contrastText',
    borderRadius: 2,            // theme.shape.borderRadius * 2
    boxShadow: 3,               // theme.shadows[3]
    typography: 'body2',        // spreads theme.typography.body2
  }}
/>

<Button sx={{ textTransform: 'none', '&:hover': { bgcolor: 'secondary.main' } }}>
  Save
</Button>

The shortcuts map to theme keys: spacing (p, m, gap, ...), palette (color, bgcolor, borderColor), borderRadius, boxShadow, typography, zIndex, and sizing (width: '50%', width: 1/2). Anything else is passed through as plain CSS.

Responsive values

Give a property an object keyed by breakpoint, or an array:

JSX
// Real Material UI, read-only
<Box sx={{
  width: { xs: '100%', sm: 360, md: 480 },
  flexDirection: { xs: 'column', md: 'row' },
  display: 'flex',
  p: [1, 2, 3], // array form: xs, sm, md
}} />

Mobile-first rules apply: sm: 360 means "from sm upwards". xs is the default for every screen.

Pseudo-classes and nested selectors

JSX
// Real Material UI, read-only
<Box
  sx={{
    '&:hover': { boxShadow: 6 },
    '&.Mui-selected': { fontWeight: 700 },
    '& .title': { letterSpacing: 1 },       // a descendant
    '& > *:not(:last-child)': { mb: 1 },    // direct children
    '@media print': { display: 'none' },
  }}
/>

& stands for the element itself. MUI components mark states with global class names such as Mui-selected, Mui-disabled, Mui-focused, and you can target them from sx.

Function and array forms

When you need the theme object itself, pass a function. An array lets you combine a base style with conditional pieces:

JSX
// Real Material UI, read-only
<Box
  sx={[
    { p: 2, borderRadius: 1 },
    (theme) => ({ border: `1px solid ${theme.palette.divider}` }),
    isActive && { bgcolor: 'action.selected' },
    ...(Array.isArray(extraSx) ? extraSx : [extraSx]),
  ]}
/>

The array form is the correct way to merge an sx that a parent passes in with your own default styles. Spreading two objects would hide any callbacks or arrays.

Try it: a tiny sx interpreter

The stand-in below turns an sx-like object into inline styles. It understands spacing shortcuts, palette strings such as 'primary.main', and breakpoint objects (using the preview's current width). Change the object and read the CSS it produces.

Interpreting an sx object

The styled() API

styled() creates a new component with CSS attached. It takes a base (an HTML tag string or any component) and returns a function that accepts an object or a callback receiving { theme, ...props }.

JSX
// Real Material UI, read-only
import { styled } from '@mui/material/styles';
import Button from '@mui/material/Button';

const BrandButton = styled(Button)(({ theme }) => ({
  borderRadius: 999,
  paddingInline: theme.spacing(3),
  textTransform: 'none',
  '&:hover': { backgroundColor: theme.palette.primary.dark },
}));

const Dot = styled('span', {
  shouldForwardProp: (prop) => prop !== 'online',
})(({ theme, online }) => ({
  width: 10,
  height: 10,
  borderRadius: '50%',
  display: 'inline-block',
  backgroundColor: online ? theme.palette.success.main : theme.palette.grey[400],
}));

<BrandButton variant="contained">Subscribe</BrandButton>
<Dot online />

shouldForwardProp

A custom prop such as online would be passed down to the DOM element and React would warn about an unknown attribute. Use shouldForwardProp to keep it out of the DOM. MUI's styled already filters ownerState, theme, sx and as.

Variants in styled

For a component that has a few modes, give the callback an array of variants. Each has a props match and a style:

JSX
// Real Material UI, read-only
const Tag = styled('span')(({ theme }) => ({
  padding: theme.spacing(0.5, 1.5),
  borderRadius: theme.shape.borderRadius,
  variants: [
    { props: { tone: 'info' }, style: { background: theme.palette.info.light } },
    { props: { tone: 'danger' }, style: { background: theme.palette.error.light } },
  ],
}));

Try it: a styled helper

This stand-in writes the styled pattern in plain React: a factory that takes a base and a function from props to style, filters unknown props, and supports variants.

A styled() factory with shouldForwardProp

sx or styled?

Situation Use
A one-off tweak on a single element sx
Styles that depend on the theme in a quick way sx with shortcuts
A style used in many places, or a named component styled()
Styles driven by several props with variants styled()
Styling a part of a MUI component (slotProps) sx inside slotProps
Changing every Button in the app The theme (next lesson)

Performance note: sx is evaluated at runtime on each render and generates a class; a styled component also generates classes but its base styles are computed once per distinct set of props. For the hot path (a table cell rendered 5,000 times), prefer styled or a plain class. See Rendering Performance and sx Cost.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In sx, what does bgcolor: 'primary.main' resolve to?

    The sx prop treats color keys as palette paths, so 'primary.main' becomes the theme color.
  2. 2. What is the right way to merge a parent's sx into your own defaults?

    sx can be an object, a function or an array. Spreading would break functions and arrays; the array form keeps them all.
  3. 3. Why use shouldForwardProp in styled()?

    A custom prop like online is for styling only. If it is passed to a DOM tag, React warns about an unknown attribute.
  4. 4. What does sx={{ width: { xs: '100%', md: 480 } }} mean?

    Breakpoint keys are mobile-first: each value applies from that breakpoint upwards.

Summary

  • sx is a theme-aware style prop with shortcuts (p, bgcolor, borderRadius), responsive objects and nested selectors.
  • Use the array form to merge sx values safely.
  • styled() builds reusable components; use shouldForwardProp for styling-only props and variants for modes.
  • Choose sx for one-offs and styled for reuse; use the theme for app-wide changes.

Next: Component Overrides and Variants