Reputation: 141
I am trying to achieve a background color change when scrolling, so I need to use a data-bg
attribute like this in my HTML markup:
<div class="section" data-bg="#ccff00">
How can I use a SCSS/Sass variable instead of the Hex code? For example:
<div class="section" data-bg="$background-color">
So when I change the variables this color also changes without having to change the HTML markup.
Upvotes: 1
Views: 6050
Reputation: 1087
An instance of data-bg attribute you can use style attribute to store the variable. In html:
<div class="section" style="--data-bg:#ccff00">
and in scss:
.section{
$bg: var(--data-bg);
width: 200px;
height: 200px;
background: $bg;
}
Upvotes: 1
Reputation: 354
No, you cannot use sass Variables in Data Attribute directly but there is an indirect way of doing this. In this way also you can change Variable from dark to light, and it will change the color from red to green.
But those both should be declared in your data-bg as i did. See this example.
[data-bg='dark']{
--text-color: red;
}
[data-bg='light']{
--text-color: green;
}
div {
color: var(--text-color);
}
<div data-bg="light"> testing green</div>
<div data-bg="dark"> testing red</div>
Upvotes: 1
Reputation: 2390
You can add your variable into the :root
selector (like Bootstrap do),
and use it with the css
function var()
.
:root {
--bg-color: $background-color;
--text-color: $text-color;
}
If you want to get the value using jQuery
:
jQuery(':root').css('--bg-color');
:root {
--bg-color: #f00;
--text-color: #0f0;
}
section {
height: 100px;
color: var(--text-color);
background-color: var(--bg-color);
}
<section>
Lorem ipsum ...
</section>
Upvotes: 1