February 6, 2023

Introduction

This post will show you how to set variables in CSS as well as in SASS, using the SCSS syntax.

Examples

HTML Code

<div class="buttongroup">
<button theme="dark">Dark</button>
<button theme="light">Light</button>
<button theme="cute">Cute</button>
</div>

<main id="dark">
<h1> <span>A Button controlled theme</span></h1>
</main>

CSS Solution

$darkColor: #010311;

@mixin buttonTheme($bgColor: $darkColor, $fontColor: white) {
padding: 25px;
border: none;
cursor: pointer;
box-shadow:0px 0px 4px 0px #b5b5b5;
background: $bgColor;
color: $fontColor;
}

.buttongroup {
position: absolute;
top: 0;
button {
&[theme="dark"] {
@include buttonTheme;
}
&[theme="light"] {
@include buttonTheme(#f3f0f0, black);
}
&[theme="cute"] {
@include buttonTheme(pink, black);
}
}
}

@mixin theme($themeBg: $darkColor, $fontColor: white) {
background: $themeBg;
color: $fontColor;
}

main {
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
display:grid;
grid-template-columns: repeat(8, 1fr);
grid-template-rows: repeat(8, 1fr);
h1{
grid-column: 4/span 6;
grid-row: 4/span 6;
span{
background:#ffeb3b;
}
}
&#dark {
@include theme;
}
&#light {
@include theme(gray, black);
}
&#cute {
@include theme(
url("https://img.freepik.com/free-vector/hand-drawn-minimal-background_23-2148999828.jpg?w=2000"),
black
);
}
}

Embed Click action to buttons

const main = document.querySelector("main")
for(const node of document.querySelectorAll("[theme]")){
node.addEventListener("click", (e) => {
const theme= e.target.innerText.toLowerCase();
main.id = theme;
})
}

Result

See the Pen
Untitled
by Comfort (@ajalacomfort16)
on CodePen.

Editor’s notes

You can also add the click function using inline syntax as an alternative for the solution.

References

Sass Guide