Reputation: 1927
I have a website built on SASS. There're certain variables I want to change while switching between light and dark themes, but all variables get compiled and converted to its original value. Hence, I don't know how to change SASS variables while changing themes.
Assuming I have following variables in style.scss
:
$mainColor: #eaeaea;
$secondaryColor: #fff;
$mainText: black;
$secondaryText: #2a3a47;
$borderColor: #c1c1c1;
$themeDotBorder: #24292e;
$previewBg: rgba(251, 249, 243, 0.8);
$previewShadow: #f9ead6;
$buttonColor: #0a0a0a;
How do I change these variables while switching themes. I can create two separate css files but that would be redundant code. Can you help me?
Upvotes: 2
Views: 6493
Reputation: 19128
Depending on your build process and requirements for older browsers, for example ie11.
Themes becomes easier with css custom properties (css variables). The basic idea is that you have your variables, and on theme change you change the color of the variables.
In my very very basic example the following things happen and why.
.dark-theme
What happens here is that in .dark-theme
we change the variables to the dark theme colors. That is the basics of it and will get you far.
Just a note, the approach on saving the theme all depends on what kind of site you have SPA, Wordpress, .NET ect. I seen mentions about saving it in the database and user, that kinda don't hold up if you don't have user signing. One approach is to save it in the browsers local storage and read it when you load the page.
const themeSwitcherButton = document.querySelector('.js-theme-switcher')
themeSwitcherButton.addEventListener('click', function() {
const body = document.querySelector('body')
if (body.classList.contains('dark-theme')) {
body.classList.remove('dark-theme')
} else {
body.classList.add('dark-theme')
}
})
:root {
--primary-color: deepskyblue;
}
body.dark-theme {
--primary-color: deeppink;
}
.block {
margin-bottom: 3rem;
padding: 2rem;
background-color: var(--primary-color);
}
<body>
<p class="block">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima quos odio atque excepturi, aut voluptate. Similique autem, eos rem cum tenetur perspiciatis voluptatibus reprehenderit cumque, inventore, nam laudantium fugiat molestias eveniet sit commodi deleniti. Ipsa eum animi, excepturi tempore placeat.
</p>
<button class="js-theme-switcher">Theme switcher</button>
</body>
Upvotes: 4
Reputation: 105
use css variables instead of sass one
--mainColor: #eaeaea;
and
color: var(--mainColor);
to use it
edit:
to change dynamically css variables
var bodyStyles = document.body.style;
bodyStyles.setProperty('--mainColor', 'white');
if variables was declared on body element
Upvotes: -1