Top Related Projects
Quickly build HTML emails with Tailwind CSS.
MJML: the only framework that makes responsive-email easy
A few simple, but solid patterns for responsive HTML email templates and newsletters. Even in Outlook and Gmail.
A free simple responsive HTML email template
Rock-solid transactional email templates for applications.
Quick Overview
Juice is a CSS inliner tool that converts external CSS styles into inline styles for HTML elements. It's particularly useful for creating HTML emails, where inline styles are often necessary for consistent rendering across different email clients. Juice can be used as a Node.js library or as a command-line tool.
Pros
- Simplifies the process of creating HTML emails with consistent styling
- Supports both Node.js library and command-line usage
- Handles complex CSS selectors and media queries
- Actively maintained and widely used in the email development community
Cons
- May require additional configuration for complex CSS structures
- Can increase the size of HTML files due to inline styles
- Limited support for some advanced CSS features
- Potential performance impact on large HTML files with extensive styling
Code Examples
- Basic usage as a Node.js library:
const juice = require('juice');
const html = '<style>div{color:red;}</style><div>Hello World!</div>';
const result = juice(html);
console.log(result);
// Output: <div style="color: red;">Hello World!</div>
- Using Juice with options:
const juice = require('juice');
const html = '<style>div{color:red;}</style><div>Hello World!</div>';
const options = {
removeStyleTags: false,
preserveMediaQueries: true
};
const result = juice(html, options);
console.log(result);
// Output: <style>@media screen and (min-width: 480px) {...}</style><div style="color: red;">Hello World!</div>
- Using Juice with external CSS file:
const juice = require('juice');
const fs = require('fs');
const html = '<div>Hello World!</div>';
const css = fs.readFileSync('styles.css', 'utf8');
const result = juice.inlineContent(html, css);
console.log(result);
// Output: <div style="color: red; font-size: 16px;">Hello World!</div>
Getting Started
To use Juice in your Node.js project:
- Install Juice:
npm install juice
- Use it in your code:
const juice = require('juice');
const html = '<style>div{color:red;}</style><div>Hello World!</div>';
const result = juice(html);
console.log(result);
For command-line usage, install Juice globally:
npm install -g juice
Then use it from the command line:
juice input.html output.html
Competitor Comparisons
Quickly build HTML emails with Tailwind CSS.
Pros of Maizzle
- More comprehensive framework for email development, offering a complete build process
- Tailwind CSS integration for rapid, utility-first styling
- Advanced features like AMP email support and component-based architecture
Cons of Maizzle
- Steeper learning curve due to its more complex structure
- Requires Node.js environment, which may not be suitable for all developers
- Less lightweight compared to Juice's focused inlining approach
Code Comparison
Maizzle (config.js):
module.exports = {
build: {
templates: {
source: 'src/templates',
destination: {
path: 'build_production',
},
},
},
}
Juice (usage example):
const juice = require('juice');
const html = '<style>div{color:red;}</style><div>Hello World!</div>';
const result = juice(html);
console.log(result);
Maizzle provides a more structured approach with configuration files and a build process, while Juice focuses on a simple API for CSS inlining. Maizzle offers a full-featured email development environment, whereas Juice is a lightweight tool for a specific task. The choice between them depends on project requirements and developer preferences.
MJML: the only framework that makes responsive-email easy
Pros of MJML
- More comprehensive and feature-rich, offering a complete framework for responsive email design
- Provides a higher-level abstraction with custom components, making it easier for non-technical users
- Includes a live editor and preview functionality for real-time development
Cons of MJML
- Steeper learning curve due to its custom syntax and components
- Larger output file size compared to Juice's lightweight approach
- May be overkill for simple email templates or projects with minimal styling needs
Code Comparison
MJML:
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-text>Hello World</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>
Juice:
<style>
.text { color: blue; }
</style>
<div class="text">Hello World</div>
Summary
MJML is a comprehensive email framework with custom components and a higher level of abstraction, making it suitable for complex, responsive email designs. Juice, on the other hand, is a simpler tool focused on inlining CSS, making it more lightweight and easier to integrate into existing workflows. The choice between the two depends on the project's complexity and the team's familiarity with email development.
A few simple, but solid patterns for responsive HTML email templates and newsletters. Even in Outlook and Gmail.
Pros of Cerberus
- Offers multiple responsive email templates for different use cases
- Includes extensive documentation and best practices for email design
- Provides both HTML and CSS inlining options for better compatibility
Cons of Cerberus
- Less actively maintained compared to Juice (last update over a year ago)
- Focuses primarily on email templates rather than a comprehensive CSS inlining solution
- May require more manual customization for specific use cases
Code Comparison
Cerberus (HTML template example):
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="padding: 20px; font-family: sans-serif; font-size: 15px; line-height: 20px; color: #555555;">
<h1 style="margin: 0 0 10px 0; font-family: sans-serif; font-size: 25px; line-height: 30px; color: #333333; font-weight: normal;">Heading 1</h1>
<p style="margin: 0;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</td>
</tr>
</table>
Juice (JavaScript usage example):
const juice = require('juice');
const html = '<style>div{color:red;}</style><div>Hello World!</div>';
const result = juice(html);
console.log(result);
Both projects aim to improve email compatibility, but Cerberus focuses on providing ready-to-use templates, while Juice offers a programmatic approach to CSS inlining.
A free simple responsive HTML email template
Pros of responsive-html-email-template
- Ready-to-use template with a responsive design
- Includes inline CSS for better email client compatibility
- Simple and lightweight, easy to customize
Cons of responsive-html-email-template
- Limited to a single template design
- Requires manual updates and maintenance
- Less flexibility compared to a CSS inlining tool
Code Comparison
responsive-html-email-template:
<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width:600px;">
<tr>
<td align="center" valign="top" style="padding: 40px 10px 40px 10px;">
<a href="http://www.example.com" target="_blank">
<img alt="Logo" src="http://www.example.com/logo.jpg" width="40" height="40" style="display: block; width: 40px; max-width: 40px; min-width: 40px; font-family: 'Lato', Helvetica, Arial, sans-serif; color: #ffffff; font-size: 18px;" border="0">
</a>
</td>
</tr>
</table>
juice:
const juice = require('juice');
const html = '<style>div{color:red;}</style><div>Hello World!</div>';
const result = juice(html);
console.log(result);
The responsive-html-email-template provides a complete HTML structure with inline styles, while juice is a tool that converts CSS to inline styles, offering more flexibility for different HTML structures.
Rock-solid transactional email templates for applications.
Pros of postmark-templates
- Offers a wide range of pre-designed email templates for various purposes
- Includes both HTML and plain text versions of templates
- Provides responsive designs optimized for different devices and email clients
Cons of postmark-templates
- Limited to email-specific use cases, less versatile for general web development
- Requires more manual customization for branding and specific needs
- Less frequent updates compared to juice
Code Comparison
postmark-templates (HTML email template snippet):
<table class="email-content" width="100%" cellpadding="0" cellspacing="0" role="presentation">
<tr>
<td class="email-masthead">
<a href="{{product_url}}" class="f-fallback email-masthead_name">
{{product_name}}
</a>
</td>
</tr>
<!-- Email Body -->
<tr>
<td class="email-body" width="100%" cellpadding="0" cellspacing="0">
juice (CSS inlining example):
const juice = require('juice');
const html = '<style>div{color:red;}</style><div>Hello World!</div>';
const inlined = juice(html);
console.log(inlined);
// Output: <div style="color: red;">Hello World!</div>
postmark-templates focuses on providing ready-to-use email templates, while juice is a tool for inlining CSS in HTML, making it more versatile for general web development. postmark-templates is ideal for quickly implementing email designs, but juice offers more flexibility for custom styling across various web projects.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Juice
Given HTML, juice will inline your CSS properties into the style
attribute.
How to use
Juice has a number of functions based on whether you want to process a file, HTML string, or a cheerio document, and whether you want juice to automatically get remote stylesheets, scripts and image dataURIs to inline.
To inline HTML without getting remote resources, using default options:
var juice = require('juice');
var result = juice("<style>div{color:red;}</style><div/>");
result will be:
<div style="color: red;"></div>
Try out the web client version
What is this useful for ?
- HTML emails. For a comprehensive list of supported selectors see here
- Embedding HTML in 3rd-party websites.
Documentation
Juice is exposed as a standard module, and from CLI with a smaller set of options.
Options
All juice methods take an options object that can contain any of these properties, though not every method uses all of these:
-
applyAttributesTableElements
- whether to create attributes for styles injuice.styleToAttribute
on elements set injuice.tableElements
. Defaults totrue
. -
applyHeightAttributes
- whether to use any CSS pixel heights to createheight
attributes on elements set injuice.heightElements
. Defaults totrue
. -
applyStyleTags
- whether to inline styles in<style></style>
Defaults totrue
. -
applyWidthAttributes
- whether to use any CSS pixel widths to createwidth
attributes on elements set injuice.widthElements
. Defaults totrue
. -
extraCss
- extra css to apply to the file. Defaults to""
. -
insertPreservedExtraCss
- whether to insert into the document any preserved@media
or@font-face
content fromextraCss
when usingpreserveMediaQueries
,preserveFontFaces
orpreserveKeyFrames
. Whentrue
order of preference to append the<style>
element is intohead
, thenbody
, then at the end of the document. When astring
the value is treated as a CSS/jQuery/cheerio selector, and when found, the<style>
tag will be appended to the end of the first match. Defaults totrue
. -
inlinePseudoElements
- Whether to insert pseudo elements (::before
and::after
) as<span>
into the DOM. Note: Inserting pseudo elements will modify the DOM and may conflict with CSS selectors elsewhere on the page (e.g.,:last-child
). -
preserveFontFaces
- preserves all@font-face
within<style></style>
tags as a refinement whenremoveStyleTags
istrue
. Other styles are removed. Defaults totrue
. -
preserveImportant
- preserves!important
in values. Defaults tofalse
. -
preserveMediaQueries
- preserves all media queries (and contained styles) within<style></style>
tags as a refinement whenremoveStyleTags
istrue
. Other styles are removed. Defaults totrue
. -
preserveKeyFrames
- preserves all key frames within<style></style>
tags as a refinement whenremoveStyleTags
istrue
. Other styles are removed. Defaults totrue
. -
preservePseudos
- preserves all rules containing pseudo selectors defined inignoredPseudos
within<style></style>
tags as a refinement whenremoveStyleTags
istrue
. Other styles are removed. Defaults totrue
. -
removeStyleTags
- whether to remove the original<style></style>
tags after (possibly) inlining the css from them. Defaults totrue
. -
resolveCSSVariables
- whether to resolve CSS variables. Defaults totrue
. -
webResources
- An options object that will be passed to web-resource-inliner for juice functions that will get remote resources (juiceResources
andjuiceFile
). Defaults to{}
. -
xmlMode
- whether to output XML/XHTML with all tags closed. Note that the input must also be valid XML/XHTML or you will get undesirable results. Defaults tofalse
.
Methods
juice(html [, options])
Returns string containing inlined HTML. Does not fetch remote resources.
html
- html string, accepts complete documents as well as fragmentsoptions
- optional, see Options above
juice.juiceResources(html, options, callback)
Callback returns string containing inlined HTML. Fetches remote resources.
html
- html stringoptions
- see Options abovecallback(err, html)
err
-Error
object ornull
html
- inlined HTML
juice.juiceFile(filePath, options, callback)
Callback returns string containing inlined HTML. Fetches remote resources.
filePath
- path to the html file to be juicedoptions
- see Options abovecallback(err, html)
err
-Error
object ornull
html
- inlined HTML
juice.juiceDocument($ [, options])
This takes a cheerio instance and performs inlining in-place. Returns the same cheerio instance. Does not fetch remote resources.
$
- a cheerio instance, be sure to use the same cheerio version that juice usesoptions
- optional, see Options above`
juice.inlineContent(html, css [, options])
This takes html and css and returns new html with the provided css inlined.
It does not look at <style>
or <link rel="stylesheet">
elements at all.
html
- html stringcss
- css stringoptions
- optional, see Options above
juice.inlineDocument($, css [, options])
Given a cheerio instance and css, this modifies the cheerio instance so that the provided css is inlined. It does not look at <style>
or <link rel="stylesheet">
elements at all.
$
- a cheerio instance, be sure to use the same cheerio version that juice usescss
- css stringoptions
- optional, see Options above
Global settings
juice.codeBlocks
An object where each value has a start
and end
to specify fenced code blocks that should be ignored during parsing and inlining. For example, Handlebars (hbs) templates are juice.codeBlocks.HBS = {start: '{{', end: '}}'}
. codeBlocks
can fix problems where otherwise juice might interpret code like <=
as HTML, when it is meant to be template language code. Note that codeBlocks
is a dictionary which can contain many different code blocks, so don't do juice.codeBlocks = {...}
do juice.codeBlocks.myBlock = {...}
juice.ignoredPseudos
Array of ignored pseudo-selectors such as 'hover' and 'active'.
juice.widthElements
Array of HTML elements that can receive width
attributes.
juice.heightElements
Array of HTML elements that can receive height
attributes.
juice.styleToAttribute
Object of style property names (key) to their respective attribute names (value).
juice.tableElements
Array of table HTML elements that can receive attributes defined in juice.styleToAttribute
.
juice.nonVisualElements
Array of elements that will not have styles inlined because they are not intended to render.
juiceClient.excludedProperties
Array of css properties that won't be inlined.
Special markup
data-embed
When a data-embed
attribute is present on a stylesheet <link>
that has been inlined into the document as a <style></style>
tag by the web-resource-inliner juice will not inline the styles and will not remove the <style></style>
tags.
This can be used to embed email client support hacks that rely on css selectors into your email templates.
CLI Options
To use Juice from CLI, run juice [options] input.html output.html
For a listing of all available options, just type juice -h
.
Note that if you want to just type
juice
from the command line, you shouldnpm install juice -g
so it is globally available.
CLI Options:
The CLI should have all the above options with the names changed from camel case to hyphen-delimited, so for example extraCss
becomes extra-css
and webResources.scripts
becomes web-resources-scripts
.
These are additional options not included in the standard juice
options listed above:
--css [filepath]
will load and inject CSS intoextraCss
.--options-file [filepath]
will load and inject options from a JSON file. Options from the CLI will be given priority over options in the file when there is a conflict.codeBlocks
is optionally supported in the options file if you include it. This will allow you to support different template languages in a build process.
Running Juice in the Browser
Attempting to Browserify require('juice')
fails because portions of Juice and its dependencies interact with the file system using the standard require('fs')
. However, you can require('juice/client')
via Browserify which has support for juiceDocument
, inlineDocument
, and inlineContent
, but not juiceFile
, juiceResources
, or inlineExternal
. Note that automated tests are not running in the browser yet.
License
MIT Licensed, see License.md
3rd-party
- Uses cheerio for the underlying DOM representation.
- Uses mensch to parse out CSS and Slick to tokenize them.
- Icon by UnheardSounds
Top Related Projects
Quickly build HTML emails with Tailwind CSS.
MJML: the only framework that makes responsive-email easy
A few simple, but solid patterns for responsive HTML email templates and newsletters. Even in Outlook and Gmail.
A free simple responsive HTML email template
Rock-solid transactional email templates for applications.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot