When it comes to customizing themes based on different requirements and older browser compatibility, such as IE11, there are various approaches you can take.
One effective way to simplify theme customization is by using CSS custom properties, also known as CSS variables. The concept revolves around defining variables for various style properties and updating them dynamically when the theme changes.
In a basic example like mine, the process involves the following steps:
- Define the default theme variables at the root level of your stylesheet.
- Create a class that represents the specific theme, for instance,
.dark-theme
.
- Add a class to the body element when switching to the dark theme using JavaScript or a similar method based on your server-side setup. In my demo, I accomplish this using JavaScript.
The key idea behind this approach is that by applying the .dark-theme
class, you can update the variable values to reflect the dark theme colors, thereby achieving a significant portion of the desired styling changes.
It's worth noting that the implementation strategy for saving and persisting the selected theme may vary depending on the type of website architecture you're working with, whether it's a single-page application, WordPress site, .NET platform, etc. Storing the theme preference in local storage rather than user-specific databases can be a viable option if user authentication isn't a core requirement.
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>