"Compile" CSS into HTML as inline styles

strager picture strager · Feb 4, 2011 · Viewed 13k times · Source

I am writing an e-mail HTML template, and some e-mail clients do not support <style> for specifying CSS. The only alternative for applying CSS is to use inline styles (style attribute). Is there a tool or library (Node.JS) for applying a stylesheet to some HTML and getting back the HTML with the styles applied?

The tool does not have to support many selectors; id, class, and element name selectors should be sufficient for my needs.

Example of what is needed:

// stylesheet.css
a { color: red; }

// email.html
<p>This is a <a href="http://example.com/">test</a></p>

// Expected result
<p>This is a <a href="http://example.com/" style="color: red;">test</a></p>

Answer

Jed Watson picture Jed Watson · Oct 21, 2012

I think juice is what you're looking for.

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

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

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

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