<div id="theme-toggle"></div>
:root {
color-scheme: only dark;
--bg-color: #1b1a19;
--bg-color-alt: #333;
--color: #fff;
}
[data-theme="light"] {
color-scheme: only light;
--bg-color: #f1f1f1;
--bg-color-alt: #fff;
--color: #222;
}
body {
background: var(--bg-color);
color: var(--color);
font-size: 18px;
}
#theme-toggle {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
cursor: pointer;
border-radius: 34px;
background-color: var(--bg-color-alt);
transition: .4s;
transition: .4s;
}
#theme-toggle:hover, #theme-toggle:focus {
box-shadow: 0 0 3px 2px #337ab7;
}
#theme-toggle:after {
content: '';
position: absolute;
height: 26px;
width: 26px;
right: 4px;
bottom: 4px;
border-radius: 50%;
background: url('//api.iconify.design/mi/moon.svg?color=white') no-repeat center;
background-color: var(--bg-color);
transition: .4s;
transition: .4s;
}
[data-theme="light"] #theme-toggle {
background-color: var(--bg-color-alt);
}
[data-theme="light"] #theme-toggle:after {
background-image: url('//api.iconify.design/mi/sun.svg');
transform: translateX(-26px);
transform: translateX(-26px);
transform: translateX(-26px);
}
/* Theme toggle */
const theme = {
current: localStorage.getItem('theme') ?? null,
update: function() {
if (this.current === null && window.matchMedia('(prefers-color-scheme: light)').matches) {
this.current = 'light';
}
localStorage.setItem('theme', this.current);
document.documentElement.setAttribute('data-theme', this.current);
},
toggle: function() {
this.current = (this.current === 'dark' ? 'light' : 'dark');
this.update();
}
};
theme.update();
document.getElementById('theme-toggle').addEventListener('click', function() {
theme.toggle();
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.