In this talk, we'll walk through refactoring a standard set of vanilla CSS into code using custom properties.
You've probably seen and written this code hundreds of time. You've probably also been fancier with it...
.button {
background-color: tomato;
color: white;
display: inline-block;
padding: .5rem 1rem;
border-radius: 3px;
text-decoration: none;
}
This is a button style
Let's make the styles more flexible using custom properties
We use the syntax --variable-name: variable-value
to set a variable and var(--variable-name)
to get the variable value. When we set values that we want to be globally accessed, we set them on the :root
pseudo-element.
:root {
--button-background: tomato;
--button-foreground: white;
--button-display: inline-block;
--button-padding: .5rem 1rem;
--button-corners: 3px;
--button-decoration: none;
--button-text-align: center;
}
.button-withvars {
background-color: var(--button-background);
color: var(--button-foreground);
display: var(--button-display);
padding: var(--button-padding);
border-radius: var(--button-corners);
text-decoration: var(--button-decoration);
text-align: var(--button-text-align);
}
This is a button style
We may have set the variables on the document's root, but we can update them at various scope levels throughout our CSS. We don't even have to change button classes. We can do this by one of its parents' classes!
<div class="container special">
<a href="#" class="button-withvars">
This is a button style
</a>
</div>
.special {
--button-background: lightblue;
--button-foreground: #333;
--button-display: block;
}
This is a button style
Dark mode anyone?
let darkModeToggle = document.querySelectorAll('.darkMode');
darkModeToggle.forEach(toggler => toggler.addEventListener('click', e => {
e.preventDefault();
document.documentElement.style.setProperty('--color', '#fff');
document.documentElement.style.setProperty('--bg-color', '#333');
document.documentElement.style.setProperty('--button-background', '#7d483e');
document.documentElement.style.setProperty('--button-foreground', '#eee');
}));
let darkModeToggle = document.querySelectorAll('.darkModeToggle');
let body = document.querySelector('body');
darkModeToggle.forEach(toggler => toggler.addEventListener('click', e => {
e.preventDefault();
body.classList.toggle('darkMode')
}));
.darkMode {
--button-background: #7d483e;
--button-foreground: #eee;
--color: #fff;
--bg-color: #333;
}
Toggle Dark Mode
Let's use JS to allow a user to adjust the site's theme on the fly! See the CodePen Panels for the code for this one. It's a lot for this little window!