Created
January 6, 2023 00:57
-
-
Save Cinedin/df7ef59389d213220bb83c05f72055ee to your computer and use it in GitHub Desktop.
VueJS: Color scheme switcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.light-theme() { | |
--display-light: none; | |
--display-dark: block; | |
--color-background: #ddd; | |
--color-foreground: #333; | |
} | |
.dark-theme() { | |
--display-light: block; | |
--display-dark: none; | |
--color-background: #333; | |
--color-foreground: #ddd; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div id="scheme-switch"> | |
<button type="button" id="scheme-switch--light" @click="setLightTheme"> | |
<slot name="light">Light theme</slot> | |
</button> | |
<button type="button" id="scheme-switch--dark" @click="setDarkTheme"> | |
<slot name="dark">Dark theme</slot> | |
</button> | |
</div> | |
</template> | |
<script setup> | |
const theme = localStorage.getItem('theme') | |
theme === 'light' && setLightTheme() | |
theme === 'dark' && setDarkTheme() | |
function setLightTheme() { | |
localStorage.setItem('theme', 'light') | |
document.body.classList.remove('dark') | |
document.body.classList.add('light') | |
} | |
function setDarkTheme() { | |
localStorage.setItem('theme', 'dark') | |
document.body.classList.remove('light') | |
document.body.classList.add('dark') | |
} | |
</script> | |
<style scoped lang="less"> | |
#scheme-switch { | |
position: absolute; | |
bottom: 0; | |
right: 0; | |
z-index: 1000; | |
background-color: var(--color-foreground); | |
border-radius: 3px 0 0 0; | |
font-size: .8rem; | |
button { | |
&, &:hover, &:focus { | |
padding: 3px 5px; | |
background-color: transparent; | |
color: var(--color-background); | |
border: none; | |
outline: none; | |
} | |
} | |
&--light { | |
display: var(--display-light); | |
} | |
&--dark { | |
display: var(--display-dark); | |
} | |
} | |
</style> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@import (reference) './color-scheme'; | |
@media (prefers-color-scheme: light) { | |
:root { | |
.light-theme(); | |
} | |
} | |
@media (prefers-color-scheme: dark) { | |
:root { | |
.dark-theme(); | |
} | |
} | |
body { | |
&.light { | |
.light-theme(); | |
} | |
&.dark { | |
.dark-theme(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment