Dark Theme for Your Knack Apps

Here is a simple way to add a Dark Theme/Dark Mode to your Knack apps.

Here is what you’ll be creating:

dark-mode-demo

Step 1:
Create a Page and call it Dark Mode:

Step 2:

Add this code to your CSS:

/* Dark Mode */

html[theme='dark-mode'] {
  filter: invert(1) hue-rotate(180deg);
}

html[theme='dark-mode'] img {
  filter: invert(1) hue-rotate(180deg);
}

html {
  transition: color 300ms, background-color 300ms;
}

Step 3:
Add this code to your JavaScript:

/* Dark Mode */
$(document).on('knack-scene-render.any', function(event, scene) {
  const darkModeButton = $('a[data-kn-slug="#dark-mode"]') // Replace "dark-mode" with whatever your Page URL is from Step 1
  darkModeButton.removeAttr('href')

  darkModeButton.on('click', () => {
    let theme = $('html').attr('theme')
    if (theme == 'dark-mode') {
      $('html').attr('theme', '')
    } else {
      $('html').attr('theme', 'dark-mode')
    }
  })
})

Congratulations! Your app now has a Dark Mode. :crescent_moon:

To improve this further you’ll probably want to make Dark Mode-specific CSS adjustments but the steps described here will give you a great start.

If you want help adding dark mode to your app—or other Design & UX features—feel free to reach out.

Ian
Knack Pros

6 Likes

Love it, thanks for sharing! The view button (like the edit, or delete buttons) turn from white font to black font. How could I modify the CSS to keep the buttons spared from the font text change when switch back and forth on dark and light mode?

Happy it helped you @Christian. I’m planning to do a new Dark Mode post because the method described here is for simple cases only—it does not allow the ability to spare the font color when switching back and forth, at least not to my knowledge. :+1:

1 Like