Overriding styles with the sx prop

Our goal with Primer React is to hit the sweet spot between providing too little and too much styling flexibility; too little and the design system is too rigid, and too much and it becomes too difficult to maintain a consistent style. Our components are designed to cover common usage patterns, but sometimes a component just isn't quite flexible enough to look the way you need it to look. For those cases, we provide the sx prop.

The sx prop allows ad-hoc styling that is still theme-aware. Declare the styles you want to apply in camelCase object notation, and try to use theme values in appropriate CSS properties when possible. If you've passed a custom theme using ThemeProvider or a theme prop, the sx prop will honor the custom theme. For more information on theming in Primer React, check out the Primer Theme documentation.

When to use the sx prop

The sx prop provides a lot of power, which means it is an easy tool to abuse. To best make use of it, we recommend following these guidelines:

  • Use the sx prop for small stylistic changes to components. For more substantial changes, consider abstracting your style changes into your own wrapper component.
  • Avoid nesting and pseudo-selectors in sx prop values when possible.

Basic example

This example demonstrates applying a bottom border to Heading, a component that does not receive BORDER system props. The borderBottomWidth value comes from theme.borderWidths and borderBottomColor comes from theme.colors.

Responsive values

Values in the sx prop can be provided as arrays to provide responsive styling.

This generates the following CSS:

.Box-hsdYAF {
background-color: var(--bgColor-open-emphasis); /* default */
padding: 8px;
color: var(--fgColor-onEmphasis);
border-radius: 6px;
}
@media screen and (min-width: 544px /* small */) {
.Box-hsdYAF {
background-color: var(--bgColor-done-emphasis);
padding: 8px;
}
}
@media screen and (min-width: 768px /* medium */) {
.Box-hsdYAF {
background-color: var(--bgColor-accent-emphasis);
padding: 16px;
}
}
@media screen and (min-width: 1012px /* large */) {
.Box-hsdYAF {
background-color: var(--bgColor-danger-emphasis);
}
}
@media screen and (min-width: 1280px /* xlarge */) {
.Box-hsdYAF {
background-color: var(--bgColor-attention-emphasis);
}
}

Nesting, pseudo-classes, and pseudo-elements

The sx prop also allows for declaring styles based on media queries, pseudo-classes, and pseudo-elements. This example, though contrived, demonstrates the ability:

Value reference