Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 36 ยท Getting Started

The sx Prop Basics

Style Material UI components with the sx prop: spacing and color shorthands, theme-aware values, pseudo-selectors and responsive objects, with runnable stand-ins.

The sx prop is the fastest way to style a Material UI component. It accepts an object of CSS-like properties, adds a few handy shorthands (p, m, bgcolor), and understands your theme, so color: 'primary.main' resolves to your actual primary color. Every MUI component and Box supports it.

This lesson covers the everyday rules of sx: shorthands, theme lookups, nested selectors and responsive values. The later theming chapter compares sx with styled() in depth.

The basics

Real MUI code (read-only):

JSX
import Box from '@mui/material/Box';

export default function Card() {
  return (
    <Box
      sx={{
        p: 2,                    // padding: 16px (2 * 8px)
        mb: 3,                   // margin-bottom: 24px
        bgcolor: 'primary.main', // theme.palette.primary.main
        color: 'primary.contrastText',
        borderRadius: 2,         // 2 * theme.shape.borderRadius (default 4px) = 8px
        boxShadow: 3,            // theme.shadows[3]
      }}
    >
      Hello sx
    </Box>
  );
}

Properties are camelCase CSS (backgroundColor, fontSize). Strings are written as normal CSS values ('1px solid #ccc'). The magic is in how some values and keys are interpreted.

Spacing shorthands

Spacing keys multiply the numeric value by theme.spacing (8px by default):

Key Property
m, mt, mr, mb, ml margin and each side
mx, my horizontal / vertical margin
p, pt, pr, pb, pl, px, py padding versions
gap, rowGap, columnGap also use the spacing scale

So p: 2 is 16px, px: 1.5 is 12px. A string value such as p: '10%' or p: '1rem' is used as is. Negative numbers work for margins (mt: -1).

Theme-aware values

Several properties look values up in the theme:

  • Colors: color, bgcolor (also backgroundColor), borderColor accept palette paths: 'primary.main', 'text.secondary', 'error.light', 'grey.100'.
  • Typography: typography: 'h5' applies the whole theme.typography.h5 style; fontWeight: 'bold' maps to theme.typography.fontWeightBold.
  • Shape: borderRadius: 1 multiplies theme.shape.borderRadius.
  • Shadows: boxShadow: 2 picks theme.shadows[2].
  • Sizing: width: 1/2 becomes 50%; values from 0 to 1 are percentages. width: 300 is 300px.
  • z-index: zIndex: 'modal' reads theme.zIndex.modal.

Because these resolve against the active theme, switching to dark mode changes 'text.primary' and 'background.paper' automatically. That is the biggest reason to prefer sx values over hard-coded hex colors.

Stand-in: an sx engine you can play with

Our editor cannot load MUI, so here is a compact stand-in Box whose sx prop works the same way for the common cases (spacing shorthands, palette paths, fractions). Edit the sx objects and see how the numbers turn into pixels.

Stand-in: Box with sx shorthands and palette paths

Nested selectors and pseudo-classes

The object can contain selectors. & stands for the element itself:

JSX
<Box
  sx={{
    p: 2,
    border: 1,
    borderColor: 'divider',
    '&:hover': { bgcolor: 'action.hover' },
    '&:focus-visible': { outline: '2px solid', outlineColor: 'primary.main' },
    '& .title': { fontWeight: 'bold' },      // descendant with class title
    '& > p': { m: 0 },                       // direct child paragraphs
    '.dark &': { bgcolor: 'grey.900' },      // when an ancestor has class dark
  }}
>
  <span className="title">Hover me</span>
</Box>

Inside nested objects the same shorthands and theme lookups work, so '&:hover': { bgcolor: 'action.hover' } uses the theme's hover tint. For MUI's own components you can target inner parts with their state classes, for example '& .Mui-disabled' or '&.Mui-selected'. These class names are stable and documented.

Responsive values

Any sx value can be an object keyed by breakpoint (xs, sm, md, lg, xl) or an array. MUI turns it into mobile-first media queries:

JSX
<Box
  sx={{
    width: { xs: '100%', md: 400 },       // full width, then 400px from 900px up
    display: { xs: 'block', sm: 'flex' },
    flexDirection: { sm: 'column', lg: 'row' },
    p: { xs: 1, sm: 2, md: 3 },
  }}
/>

{ xs: 'a', md: 'b' } means "a from 0px up, b from 900px up", so you only list the breakpoints where the value changes. The next stand-in imitates this with real media queries; resize the preview to see it.

Stand-in: responsive and hover styles from one object

sx or styled()?

Use sx for one-off adjustments on a specific element: a margin here, a color there. Use styled() when you build a reusable styled component (const Panel = styled('div')(...)) or when many instances share the same styles. Both read the theme the same way. Two cautions:

  • sx styles are computed per render of that element. In very large lists (thousands of rows), prefer styled() or CSS classes.
  • Do not build selector keys from user input; values are fine, but selector keys should be static.

If the same sx object appears in several places, hoist it into a constant (const cardSx = { p: 2, ... }) and pass sx={cardSx}. You can also pass an array to compose them: sx={[cardSx, isActive && activeSx]}.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With the default theme, what does sx={{ p: 2 }} produce?

    Spacing keys multiply the number by theme.spacing, which defaults to 8px, so p: 2 is 16px.
  2. 2. What does color: 'primary.main' do inside sx?

    Color keys resolve palette paths, so the value follows your theme (including dark mode).
  3. 3. How do you set width to 100% on mobile and 400px from the md breakpoint up?

    An object keyed by breakpoint creates mobile-first media queries.
  4. 4. Which key targets the hover state of the element itself in sx?

    Nested selectors use & for the element itself, for example '&:hover'.
  5. 5. When is styled() usually a better choice than sx?

    styled() creates a reusable component and avoids recomputing identical sx objects in many elements.

Summary

  • sx accepts CSS-like objects plus shorthands (p, mx, bgcolor) and works on every MUI component.
  • Spacing numbers are multiplied by theme.spacing (8px); colors, typography, shadows and radii resolve through the theme.
  • Nested selectors such as '&:hover' and '& .child' live inside the same object.
  • Breakpoint objects ({ xs, sm, md }) give mobile-first responsive styles.
  • Prefer styled() for reusable components and very large lists.

Next: Buttons and Icon Buttons