PicoCSS Dynamic Templates
Pico CSS has the ability to customize the dark and light templates here is how to change the template colors with JS.
The Pico CSS template utilizes CSS variables to dynamically alter the appearance of the website. In this scenario, the intention was to extract the color information from a database and dynamically customize the visual presentation of the site. All CSS variables are defined at the :root
level and can be manipulated using JavaScript's setProperty
method, as demonstrated below.
1let color = "#00A1FE";
2
3let root = document.querySelector(":root");
4root.style.setProperty("--primary", color);
5root.style.setProperty("--primary-hover", color);
6root.style.setProperty("--primary-focus", color + "40");
7root.style.setProperty("--primary-inverse", "#fff");
To ensure that the template colors are not pre-loaded prior to dynamically setting them, it is recommended to set the template colors to transparent, as demonstrated below:
1/* Deep-purple Light scheme (Default) */
2/* Can be forced with data-theme="light" */
3:root:not([data-theme="dark"]),
4[data-theme="light"] {
5 --primary: #00000000;
6 --primary-hover: #00000000;
7 --primary-focus: #00000000;
8 --primary-inverse: #fff;
9 --logo-text: #000;
10}
11
12/* Deep-purple Dark scheme (Auto) */
13/* Automatically enabled if user has Dark mode enabled */
14@media only screen and (prefers-color-scheme: dark) {
15 :root:not([data-theme="light"]) {
16 --primary: #00000000;
17 --primary-hover: #00000000;
18 --primary-focus: #00000000;
19 --primary-inverse: #fff;
20 --logo-text: #fff;
21 }
22}
23
24/* Deep-purple Dark scheme (Forced) */
25/* Enabled if forced with data-theme="dark" */
26[data-theme="dark"] {
27 --primary: #00000000;
28 --primary-hover: #00000000;
29 --primary-focus: #00000000;
30 --primary-inverse: #fff;
31 --logo-text: #fff;
32}
33
34/* Deep-purple (Common styles) */
35:root {
36 --form-element-active-border-color: var(--primary);
37 --form-element-focus-color: var(--primary-focus);
38 --switch-color: var(--primary-inverse);
39 --switch-checked-background-color: var(--primary);
40}