Assume I have something like this:
.object {
$primary-color: blue;
h1 {
font-size: 40px;
color: $primary-color;
}
p {
font-size: 20px;
color: $primary-color;
}
}
Now I'll be having a blue object. But let's say I want to make the same object but in a red color, it might be intuitive to write
.object red {
$primary-color: red;
}
and expect all the $primary-color to change to red, but this is not valid in SCSS. What I have to write is:
.object red {
$primary-color: red;
h1 { color: $primary-color; }
p { color: $primary-color; }
}
If I do it this way, I can still keep the 40px font size in h1 and 20px in p and will change all colors to red. However, once my code gets bigger, this will become harder and harder to maintain.
Does SCSS provide any tool to make this task more modular and maintainable?
CSS Variables to the Rescue CSS variables is a standard which enables you to have variables in CSS. SCSS is compiled to CSS during compile time, and SCSS variables are replaced with resolved value during compile time, which means there is no way to change the variable during run time.
In this article, we will see how to dynamically create a CSS class and apply to the element dynamically using JavaScript. To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript.
CSS custom properties are a powerful and innovative way to bring more life to your stylesheets, introducing completely dynamic values for the first time in CSS.
For sure SCSS provide such function but you can also do it with CSS using CSS variables:
.object h1 {
font-size: 40px;
color: var(--p, blue);
}
.object p {
font-size: 20px;
color: var(--p, blue);
}
.red {
--p:red;
}
.other-color {
--p:rgb(15,185,120);
}
<div class="object">
<h1>Blue title</h1>
<p>blue text</p>
</div>
<div class="object red">
<h1>red title</h1>
<p>red text</p>
</div>
<div class="object other-color">
<h1>red title</h1>
<p>red text</p>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With