I'm wanting to know if you can use SASS variables to generate inline CSS.
I'm aware you can do the following:
$my-class: yellow;
$yellow: #ffff00;
.#{$my-class} {
color: $yellow;
}
And then inline the CSS using a Grunt task which outputs:
<div class="yellow" style="color: #ffff000;">Hello world</div>
But is it possible to use a variable:
$font-family: Arial, sans-serif;
In such a way:
<div style="font-family: $font-family;">Hello world</div>
Which would output:
<div class="font-family: Arial, sans-serif;">Hello world</div>
I'm pretty sure you can't with basic SASS but it would good to hear some thoughts on it.
CSS Variables are supported natively in all major browsers. They allow us to use real variables in the browser. Here is brief of the support table: To define a CSS Variable, it needs to be added to the :root declaration if it's global ( :root is equivalent to <html> except that :root has a higher specificity).
CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section.
To convert the SASS variable to a CSS custom property you put curly brackets around it, and a hash in front. If you've used template literals in JavaScript it's the same thing, just with a # instead of a $ (because we already have $ in the variable name).
CSS variables are included in the CSS output. CSS variables can have different values for different elements, but Sass variables only have one value at a time. Sass variables are imperative, which means if you use a variable and then change its value, the earlier use will stay the same.
You can also use CSS variables
.box {
--difference: blue;
background: red;
}
<div class="box">1</div>
<div class="box" style="background: var(--difference)">2</div>
You can use a html preprocessor such as jade together with a tool like sass-extract to accomplish this.
Here is an example where you would get the result in your example.
style.scss
$fontFamily: Arial;
template.jade
div(style="font-family: #{$fontFamily.value};") Hello world
index.js (could also be a grunt/gulp task)
const sassExtract = require('sass-extract');
const jade = require('jade');
const style = sassExtract.renderSync({ file: './style.scss' });
const html = jade.renderFile('./template.jade', style.vars.global);
console.log(html);
Outputs
<div style="font-family: Arial">Hello world</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