Theming with CSS variables
by Julien Roche
HTML
<body class="main">
<h1 class="main__title">A sample usage of theming with CSS variables</h1>
<p class="main__content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p class="main__content main__content--center">
<button class="main__content__button" type="button">Click to toggle theme</button>
</p>
</body>
CSS
:root {
--backgroundColor: black;
--borderColor: grey;
--fontColor: white;
}
html, body {
height: 100%;
margin: 0 0 0 0;
padding: 0 0 0 0;
width: 100%;
}
[data-theme="white"] {
--backgroundColor: white;
--borderColor: red;
--fontColor: black;
}
.main {
background-color: var(--backgroundColor);
color: var(--fontColor);
}
.main__title {
border-bottom: 3px solid var(--borderColor);
padding: 1em 1em 1em 1em;
}
.main__content {
padding: 0.5em 1em 0.5em 1em;
}
.main__content--center {
text-align: center;
}
.main__content__button {
background-color: var(--fontColor);
border: 1px solid var(--borderColor);
border-radius: 5px;
box-shadow: 10px 10px 10px 0px var(--borderColor);
color: var(--backgroundColor);
font-size: 2em;
font-weight: bolder;
text-align: center;
}
Babel + JSX
let toggle = false;
document
.querySelector('button')
.addEventListener('click', event => {
toggle = !toggle;
document.body.setAttribute('data-theme', toggle ? 'white' : '');
}, false);