Dark mode

accessibility, css, design, development

Dark mode can provide a number of benefits for consuming content: reduced eye strain due to emissive displays, particularly in low-light environments; reduced power consumption on some display types (e.g. OLED); reduced blue light exposure; and more. It's not always suitable but when it is, knowing how to take advantage of it is very useful. Some applications or websites allow a user to explicitly choose between light and dark modes, others respect the system settings and don't provide the ability for the user to override this.

Design considerations #

  • pay particular attention to contrast
    • Web Content Accessibility Guidelines (WCAG) requires that “the visual presentation of text… has a contrast ratio of at least 4.5:1,” except for large-scale text, which should have a contrast ratio of at least 3:1. These are from Success Criterion 1.4.3 Contrast (Minimum). Further, Success Criterion 1.4.6 Contrast (Enhanced) calls for even higher ratios of at least 7:1 and 4.5:1 respectively
    • ensure sufficient contrast between other UI elements too, not just text. If there's not sufficient contrast or separation between cards, buttons, form fields, icons, etc. the design can look very dull / washed out and negatively impact usability
  • dark does not necessarily mean black, white text on a black background is not a great choice for most uses. For example Google's Material design recommends #121212 as a base

Carbon Design System #

Implementing dark mode with the Carbon Design System and CSS custom properties.

Example from Tekton Dashboard:

$feature-flags: (
  enable-css-custom-properties: true
);

@import '~@carbon/themes/scss/themes';

:root, .tkn--theme-light {
  @include carbon--theme($carbon--theme--g10, true);
}

@mixin tkn--theme-dark {
  @include carbon--theme($carbon--theme--g90, true) {
    @include emit-component-tokens($notification-colors);
    @include emit-component-tokens($tag-colors);
  };
}

.tkn--theme-dark {
  @include tkn--theme-dark;
}

@media (prefers-color-scheme: dark) {
  .tkn--theme-system {
    @include tkn--theme-dark;
  }
}

The carbon--theme mixin emits a set of CSS custom properties definining the various design tokens (colour, spacing, etc.) which are used by the Carbon component styles later on.

The prefers-color-scheme media query is used to detect whether the user's OS has enabled dark mode. This setting is honoured by using the 'system' theme class and can also be overridden using either the 'light' or 'dark' classes directly. These overrides can also be applied to specific portions of the page as needed, for example to enforce a dark log container regardless of the selected theme.

The mechanism to enable any of these modes is unimportant, and in the example linked above is controlled via a value in the browser's localStorage. In future a UI control may be provided to the user in the application settings for example.

Useful resources #

-