Class CssInliner

java.lang.Object
dev.jcputney.mjml.css.CssInliner

public final class CssInliner extends Object
Inlines CSS styles into HTML elements' style attributes.

This is a standalone utility that can be used independently of the MJML renderer. It operates on the final HTML output, matching CSS rules to elements and merging styles into inline style="" attributes.

Rules with pseudo-classes (:hover), pseudo-elements (::before), @media queries, @font-face, and @keyframes are preserved in <style> blocks rather than being inlined.

Usage

// Inline styles from <style> blocks in the HTML
String inlined = CssInliner.inline(html);

// Inline additional CSS alongside <style> blocks
String inlined = CssInliner.inline(html, additionalCss);
  • Method Details

    • inline

      public static String inline(String html)
      Inlines CSS from <style> blocks in the HTML into element style attributes. Non-inlineable rules (pseudo-classes, @media, etc.) are preserved in a single <style> block in the output.
      Parameters:
      html - the HTML string
      Returns:
      the HTML with CSS inlined
    • inline

      public static String inline(String html, String additionalCss)
      Inlines CSS from <style> blocks and additional CSS into element style attributes.
      Parameters:
      html - the HTML string
      additionalCss - optional additional CSS to inline (may be null)
      Returns:
      the HTML with CSS inlined
    • inlineAdditionalOnly

      public static String inlineAdditionalOnly(String html, String css)
      Inlines only the provided CSS into HTML elements' style attributes, without extracting or removing any existing <style> blocks from the HTML. This is used by the MJML renderer for <mj-style inline="inline"> content, where base CSS resets in the head must be preserved.
      Parameters:
      html - the HTML string
      css - the CSS to inline
      Returns:
      the HTML with the provided CSS inlined into matching elements
    • inlineAdditionalOnly

      public static String inlineAdditionalOnly(String html, HtmlElement root, String css)
      Inlines only the provided CSS into HTML elements' style attributes using a pre-parsed element tree, avoiding redundant HTML re-parsing when the tree is already available.
      Parameters:
      html - the original HTML string (for position-based modification)
      root - the pre-parsed element tree
      css - the CSS to inline
      Returns:
      the HTML with the provided CSS inlined into matching elements