Skip to content

Instantly share code, notes, and snippets.

@dvdsmpsn
Last active June 13, 2020 14:54
Show Gist options
  • Save dvdsmpsn/f5b535ac484b40178da780b8c157e131 to your computer and use it in GitHub Desktop.
Save dvdsmpsn/f5b535ac484b40178da780b8c157e131 to your computer and use it in GitHub Desktop.
Changing styles and colours with CSS custom properties (CSS variables)
license: apache-2.0
<html>
<head>
<style>
:root {
--theme-font: serif;
--theme-bg: #fff;
--theme-fg: #000;
}
body {
background-color: var(--theme-bg);
color: var(--theme-fg);
font-family: var(--theme-font);
font-size: 20px;
padding: 40px;
}
button {
border: 0;
border-radius: 4px;
padding: 10px 20px;
color: var(--theme-bg);
background-color: var(--theme-fg);
font-family: var(--theme-font);
}
@media screen and (prefers-color-scheme: dark) {
:root {
--theme-font: serif;
--theme-bg: #000;
--theme-fg: #fff;
}
}
</style>
</head>
<body>
<p>
A paragraph
</p>
<p>Serif:</p>
<button data-font="serif" data-bg="#111" data-fg="#eee">
dark on light serif
</button>
<button data-font="serif" data-bg="#eee" data-fg="#111">
light on light serif
</button>
<button data-font="serif" data-bg="#fff" data-fg="hotpink">
bright on light serif
</button>
<p>Sans-serif:</p>
<button data-font="sans-serif" data-bg="#111" data-fg="#eee">
dark on light sans-serif
</button>
<button data-font="sans-serif" data-bg="#eee" data-fg="#111">
light on light sans-serif
</button>
<button data-font="sans-serif" data-bg="#fff" data-fg="hotpink">
bright on light sans-serif
</button>
<script>
// get the buttons
const buttons = document.querySelectorAll("button");
buttons.forEach((currentValue, currentIndex, button) => {
buttons[currentIndex].addEventListener("click", function (event) {
// Read the style from the button `data-` attributes
document.documentElement.style.setProperty(
"--theme-font",
event.target.getAttribute("data-font")
);
document.documentElement.style.setProperty(
"--theme-bg",
event.target.getAttribute("data-bg")
);
document.documentElement.style.setProperty(
"--theme-fg",
event.target.getAttribute("data-fg")
);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment