Skip to main content

Light and Dark Themes

It is a common pattern to define separate light, dark and system themes to provide the ability to switch between different color schemes.

This would typically be done by defining three separate Themes:

const lightVars = {
primaryColor: 'black',
...
};
export const light = stylex.createTheme(vars, lightVars);

const darkVars = {
primaryColor: 'white',
...
};
export const dark = stylex.createTheme(vars, darkVars);

const systemVars = {
primaryColor: {
default: 'black',
'@media (prefers-color-scheme: dark)': 'white',
},
...
};
export const system = stylex.createTheme(vars, systemVars);

This pattern is well supported and will work in all browsers that support CSS variables.

Using the light-dark() CSS function

In modern browsers, we suggest using the light-dark() CSS function instead which will simplify the code and remove the need to define themes.

export const vars = stylex.defineVars({
primaryColor: 'light-dark(black, white)',
...
});

You can now control the color scheme applied by using the color-scheme CSS property.

const styles = stylex.create({
light: {
colorScheme: 'light',
},
dark: {
colorScheme: 'dark',
},
system: {
colorScheme: 'light dark',
},
});

<div {...stylex.props(styles[colorScheme])}>
...
</div>

You can still define custom themes for other use-cases and use light-dark() within them.

Limitations

  1. The light-dark() CSS function can only be used for color values.
  2. The light-dark() function is not supported in older browsers.