Skip to content

Commit

Permalink
feat: Show light and dark theme applied using system preferences (car…
Browse files Browse the repository at this point in the history
…bon-design-system#4022)

* Show light and dark theme applied using system preferences

Modern browsers and systems allow the user to configure a preference for light and dark modes. This should be obeyed where the user has not configured a theme for the current application.

* chore: format

---------

Co-authored-by: Alison Joseph <[email protected]>
  • Loading branch information
lee-chase and alisonjoseph committed Jun 10, 2024
1 parent 4980ea2 commit 8dfa466
Showing 1 changed file with 89 additions and 0 deletions.
89 changes: 89 additions & 0 deletions src/pages/elements/themes/code.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,95 @@ Themes can also be extended with your own custom tokens:
);
```

#### System preferences

Modern browsers and systems have adopted the idea of dark and light themes
applied at a system level. Where no user preference has been specified their
system level theme should be matched.

For example applying `g10` or `g100` automaticcally based on system preferences.

```scss
@use '@carbon/themes/scss/themes' as *;
@use '@carbon/themes';

/* system preference theme by default */
:root {
@include themes.theme($g10);
}

@media (prefers-color-scheme: dark) {
:root {
@include themes.theme($g100);
}
}

/* user has configured a theme preference for the current page/app */
[data-carbon-theme='white'] {
@include themes.theme($white);
}

[data-carbon-theme='g10'] {
@include themes.theme($g10);
}

[data-carbon-theme='g90'] {
@include themes.theme($g90);
}

[data-carbon-theme='g100'] {
@include themes.theme($g100);
}
```

Some designs include a sections in the opposite theme.

```scss
@mixin theme-scheme($default, $compliment) {
/* apply default theme */
@include theme($default, true);

/* apply to the compliment theme */
[data-carbon-theme--compliment] {
@include theme($compliment, true);
}

/* apply the default theme */
/* to switch back from within a compliment */
[data-carbon-theme] {
@include theme($default, true);
}
}

/* system preference theme by default */
:root {
@include theme-scheme(themes.$g10, themes.$g100);
}

@media (prefers-color-scheme: dark) {
:root {
@include theme-scheme(themes.$g100, themes.$g10);
}
}

/* user has configured a theme preference for the current page/app */
[data-carbon-theme='white'] {
@include theme-scheme(themes.$white, themes.$g90);
}

[data-carbon-theme='g10'] {
@include theme-scheme(themes.$g10, themes.$g100);
}

[data-carbon-theme='g90'] {
@include theme-scheme(themes.$g90, themes.$white);
}

[data-carbon-theme='g100'] {
@include theme-scheme(themes.$g100, themes.$g10);
}
```

### JavaScript

If you're looking to use these themes in JavaScript, we export a variety of
Expand Down

0 comments on commit 8dfa466

Please sign in to comment.