Using SASS variables to generate inline CSS

12,587

Solution 1

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>

Solution 2

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>
Share:
12,587
abbas_arezoo
Author by

abbas_arezoo

Digital Designer who's here to learn.

Updated on June 12, 2022

Comments

  • abbas_arezoo
    abbas_arezoo almost 2 years

    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.