Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SASS variables to generate inline CSS

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.

like image 920
abbas_arezoo Avatar asked Feb 04 '15 20:02

abbas_arezoo


People also ask

Can you use CSS variables inline?

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).

How do you make an inline CSS?

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.

How do I assign a Sass variable to a variable in CSS?

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).

Can Sass use CSS variables?

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.


Video Answer


2 Answers

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>
like image 95
SuperDJ Avatar answered Oct 30 '22 23:10

SuperDJ


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>
like image 25
jgranstrom Avatar answered Oct 30 '22 23:10

jgranstrom