7

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.

6
  • you might be interested in an html preprocessor jade-lang.com/reference/conditionals Commented Feb 4, 2015 at 20:23
  • That's similar to the Kit language: incident57.com/codekit/help.html#kit however I'd like to be able to control the whole process with SASS if at all possible. Commented Feb 4, 2015 at 20:25
  • 2
    Usually use inline CSS is not a very good thing. You can check this link webdesign.about.com/od/css/a/aa073106.htm . Maybe if you explain what you are trying to do becomes easier to help you. Commented Feb 4, 2015 at 23:08
  • @PedroMoreira It's mainly for email newsletters. Commented Feb 5, 2015 at 8:41
  • Short answer, you can't. especially if it's for newsletter consider to simplify your code procedure since you already be aware of the painful email structure Commented Feb 5, 2015 at 14:05

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.