CSS variables and color theme for the site in several lines

One way to use CSS variables today


Create a site that dynamically supports light, dark and color themes.


Interactive demo



Create a base color that will change. Bind it to data-theme in html.


code examples use & from less / scss syntax


html[data-theme='green'] { --theme-color: 110; } 

Now we need the colors themselves. Or rather their brightness and saturation. To do this, we will use the hsl scheme. We put all the variables in: root.


 :root { --color: ~'hsl(var(--theme-color), 15%, 44%)'; --background-color: ~'hsl(var(--theme-color), 30%, 10%)'; } 

Here you go. Case for small. Grab the desired element and apply our variable to it.


 .class-name { color: var(--color); background-color: var(--background-color); } 

Now we will change the contrast. Replace: root with html [with attribute].


 // :root = html html { &[data-theme-style='normal'] { } &[data-theme-style='dark'] { } } 

Now for each topic we take our s, l values.


 html { &[data-theme-style='normal'] { --color: ~'hsl(var(--theme-color), 15%, 44%)'; --background-color: ~'hsl(var(--theme-color), 30%, 10%)'; } &[data-theme-style='dark'] { --color: ~'hsl(var(--theme-color), 70%, 31%)'; --background-color: ~'hsl(var(--theme-color), 3%, 3%)'; } } 



Links:
Interactive demo
Thank you Marcin Wichary for the idea.



Source: https://habr.com/ru/post/466587/


All Articles