[ACCEPTED]-Compile" CSS into HTML as inline styles-stylesheet

Accepted answer
Score: 21

I think juice is what you're looking for.

Simply 7 require it, then pass it your html and css 6 and let it do the heavy lifting for you 5 like this:

var juice = require('juice');
var inlinedcss = juice('<p>Test</p>', 'p { color: red; }');

It builds on a number of mature 4 libraries including mootools' slick, and 3 supports a broad range of selectors.

You 2 may also be interested in node-email-templates, which is a nice 1 wrapper for dynamic emails in node.

Score: 7

Here's the alive javascript projects that 5 does what you want:

  • juice. 1.7Mb with dependencies.
  • juice2. 5.9Mb with dependencies. This is a fork of juice, seems to be containing more options than juice. This one doesn't drop media queries as juice does. Sorts inline css rules alphabetically.
  • styliner. 4.0Mb with dependencies. This one uses promises instead. Have a couple of different options than juice2. Has a compact option that other ones don't have that minifies the html. Doesn't read the html file itself as others do. Also extends margin and padding shorthands. And in case you somehow modify your native objects(like if you are using sugar) I don't suggest using this till this issue is resolved.

So which one to use? Well 4 it depends on the way you write CSS. They 3 each have different support for edge cases. Better 2 check each and do some tests to understand 1 perfectly.

Score: 3

You could use jsdom + jquery to apply $('a').css({color:'red'});


Score: 3

2020 solution https://www.npmjs.com/package/inline-css

var inlineCss = require('inline-css');
var html = "<style>div{color:red;}</style><div/>";

inlineCss(html, options)
    .then(function(html) { console.log(html); });


Score: 0

Another alternative is to go back to basics. If 3 you want a link to be red, instead of

<a href="" style="color: red">my link</a>


<a href=""><font color="red">my link</font></a>

Almost 2 any browser, including the terrible BlackBerry 1 browser can handle that.

More Related questions