<div class="navbar">
<button class="btn" id="system-button">System</button>
<button class="btn" id="light-button">Light</button>
<button class="btn" id="dark-button">Dark</button>
</div>
<h1 class="title">Title</h1>
<h5 class="subtitle">Subtitle</h5>
* {
margin: 0;
padding: 0;
}
:root {
--background-main: #fefefe;
--background-secondary: #cccccc;
--color-main: #333333;
--color-secondary: #555555;
}
.dark {
--background-main: #333333;
--background-secondary: #555555;
--color-main: #fefefe;
--color-secondary: #cccccc;
}
@media (prefers-color-scheme: dark) {
.system {
--background-main: #333333;
--background-secondary: #555555;
--color-main: #fefefe;
--color-secondary: #cccccc;
}
}
body {
width: 100%;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
background: var(--background-main);
}
.navbar {
width: calc(100% - 40px);
height: 44px;
background: var(--background-secondary);
display: flex;
justify-content: flex-end;
align-items: center;
padding: 0 20px;
margin-bottom: 20px;
box-shadow: 0 6px 6px rgba(0, 0, 0, 0.3);
}
.btn {
width: 120px;
padding: 6px 12px;
margin-left: 20px;
cursor: pointer;
color: var(--color-main);
background: var(--background-main);
border: 1px solid var(--color-secondary);
border-radius: 6px;
}
.title {
font-size: 3rem;
color: var(--color-main);
}
.subtitle {
font-size: 1rem;
color: var(--color-secondary);
}
const body = document.body;
const system = document.getElementById("system-button");
const light = document.getElementById("light-button");
const dark = document.getElementById("dark-button");
system.addEventListener("click", () => setTheme("system"));
light.addEventListener("click", () => setTheme("light"));
dark.addEventListener("click", () => setTheme("dark"));
const availableThemes = ["system", "light", "dark"];
function setTheme(themeToSet) {
if (!availableThemes.includes(themeToSet)) return;
window.localStorage.setItem("theme", themeToSet);
availableThemes.forEach((theme) => {
if (theme !== themeToSet && body.classList.contains(theme))
body.classList.remove(theme);
});
if (!body.classList.contains(themeToSet)) {
body.classList.add(themeToSet);
}
}
(function loadTheme() {
const theme = window.localStorage.getItem("theme");
setTheme(theme);
})();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.