A very very small script to handle CSS theming
Change CSS theme with toggle, buttons or select using CSS Variables (CSS custom properties) and localStorage.
It saves the chosen theme in brower localStorage and loads it again when page loads.
You only need to define your theme in CSS
- You can use 3 methods:
- Then you need to define your theme in CSS
Using data-set-theme
Clicking on these buttons, sets the chosen theme and also adds the ACTIVECLASS
to the chosen button
<button data-act-class="ACTIVECLASS" data-set-theme=""></button>
<button data-act-class="ACTIVECLASS" data-set-theme="dark"></button>
<button data-act-class="ACTIVECLASS" data-set-theme="pink"></button>
<script src="https://unpkg.com/theme-change@latest/dist/btn.js"></script>
Or use NPM:
Install: npm i theme-change --save
and use it in your js file:
import {themeBtn} from "theme-change"
themeBtn()
Using data-toggle-theme
Clicking on this element, toggles between the 2 values and applies the ACTIVECLASS when dark theme is active
<button data-act-class="ACTIVECLASS" data-toggle-theme="dark,light"></button>
<script src="https://unpkg.com/theme-change@latest/dist/toggle.js"></script>
Or use NPM:
Install: npm i theme-change --save
and use it in your js file:
import {themeToggle} from "theme-change"
themeToggle()
Using data-choose-theme
set theme when <select>
changes
<select data-choose-theme>
<option value="">Default</option>
<option value="dark">Dark</option>
<option value="pink">Pink</option>
</select>
<script src="https://unpkg.com/theme-change@latest/dist/select.js"></script>
Or use NPM:
Install: npm i theme-change --save
and use it in your js file:
import {themeSelect} from "theme-change"
themeSelect()
Set your themeable style as custom properties in CSS like this:
:root {
--color-default: #fff;
/* or any other variables */
}
[data-theme='dark'] {
--color-default: #252b30;
}
[data-theme='pink'] {
--color-default: #ffabc8;
}
then use your variables on any element
body {
background-color: var(--color-default);
}
You can also define a default theme when user is using a dark theme on their OS
@media (prefers-color-scheme: dark){
--color-default: #252b30;
}
/*! purgecss start ignore */
[data-theme='dark'] {
--color-default: #252b30;
}
/*! purgecss end ignore */