Automatically convert Style Sheets to inline style

javascript convert css to inline styles
convert to inline css
inline css html template
inline css email template
inline css checker online
inline css responsive email
inline all css
inline responsive css

Don't have to worry about linked style or hover style.

I want to automatically convert files like this

body, p{font-weight:bold}

to files like this

<body style="background:red;font-weight:bold">
<p style="background:#FFC;font-weight:bold">...</p>

I would be even more interested if there was an HTML parser that would do this.

The reason I want to do this is so I can display emails that use global style sheets without their style sheets messing up the rest of my web page. I also would like to send the resulting style to web based rich text editor for reply and original message.

Here is a solution on java, I made it with the JSoup Library:

import java.util.StringTokenizer;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class AutomaticCssInliner {
     * Hecho por Grekz,
    public static void main(String[] args) throws IOException {
        final String style = "style";
        final String html = "<html>" + "<body> <style>"
                + "body{background:#FFC} \n p{background:red}"
                + "body, p{font-weight:bold} </style>"
                + "<p>...</p> </body> </html>";
        // Document doc = Jsoup.connect("").get();
        Document doc = Jsoup.parse(html);
        Elements els =;// to get all the style elements
        for (Element e : els) {
            String styleRules = e.getAllElements().get(0).data().replaceAll(
                    "\n", "").trim(), delims = "{}";
            StringTokenizer st = new StringTokenizer(styleRules, delims);
            while (st.countTokens() > 1) {
                String selector = st.nextToken(), properties = st.nextToken();
                Elements selectedElements =;
                for (Element selElem : selectedElements) {
                    String oldProperties = selElem.attr(style);
                            oldProperties.length() > 0 ? concatenateProperties(
                                    oldProperties, properties) : properties);
        System.out.println(doc);// now we have the result html without the
        // styles tags, and the inline css in each
        // element

    private static String concatenateProperties(String oldProp, String newProp) {
        oldProp = oldProp.trim();
        if (!newProp.endsWith(";"))
           newProp += ";";
        return newProp + oldProp; // The existing (old) properties should take precedence.

CSS Inliner Tool, We know that writing inline CSS is time consuming and repetitive, so we've built this conversion tool to automatically inline your email's CSS. Just paste your  We know that writing inline CSS is time consuming and repetitive, so we've built this conversion tool to automatically inline your email's CSS. Just paste your email's HTML below, click Convert, and you'll get a more email-friendly version that's ready to send.

Using jsoup + cssparser:

private static final String STYLE_ATTR = "style";
private static final String CLASS_ATTR = "class";

public String inlineStyles(String html, File cssFile, boolean removeClasses) throws IOException {
    Document document = Jsoup.parse(html);
    CSSOMParser parser = new CSSOMParser(new SACParserCSS3());
    InputSource source = new InputSource(new FileReader(cssFile));
    CSSStyleSheet stylesheet = parser.parseStyleSheet(source, null, null);

    CSSRuleList ruleList = stylesheet.getCssRules();
    Map<Element, Map<String, String>> allElementsStyles = new HashMap<>();
    for (int ruleIndex = 0; ruleIndex < ruleList.getLength(); ruleIndex++) {
        CSSRule item = ruleList.item(ruleIndex);
        if (item instanceof CSSStyleRule) {
            CSSStyleRule styleRule = (CSSStyleRule) item;
            String cssSelector = styleRule.getSelectorText();
            Elements elements =;
            for (Element element : elements) {
                Map<String, String> elementStyles = allElementsStyles.computeIfAbsent(element, k -> new LinkedHashMap<>());
                CSSStyleDeclaration style = styleRule.getStyle();
                for (int propertyIndex = 0; propertyIndex < style.getLength(); propertyIndex++) {
                    String propertyName = style.item(propertyIndex);
                    String propertyValue = style.getPropertyValue(propertyName);
                    elementStyles.put(propertyName, propertyValue);

    for (Map.Entry<Element, Map<String, String>> elementEntry : allElementsStyles.entrySet()) {
        Element element = elementEntry.getKey();
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, String> styleEntry : elementEntry.getValue().entrySet()) {
        element.attr(STYLE_ATTR, builder.toString());
        if (removeClasses) {

    return document.html();

Free Tool: CSS inliner, CSS inliner. Writing inline CSS can be a pain, so we built a tool that'll do the hard work for you. Just paste your HTML below, and we'll move all your styles inline. CSS (Cascading Style Sheet) is declared to maintain the formatting, layout and appearance of Web page elements. You can include CSS declarations in multiple locations in an HTML file, including inline, internally and optionally in an external file.

After hours of trying different manual java code solutions and not being satisfied with results (responsive media query handling issues mostly), I stumbled upon which works great as a java solution. Note that you might actually be better off running your own "premailer" server. While there is a public api to premailer, I wanted to have my own instance running that I can hit as hard as I want:

Easy to run on ec2 with just a few clicks:

git clone
cd premailer-server
eb init  (choose latest ruby)
eb create premailer-server
eb deploy
curl --data "html=<your html>" http://your.eb.url

Emogrifier by Intervals, Emogrifier solves this problem by converting CSS into HTML inline style serif; } div#container { margin: 1em auto; } h1 { font-weight: bold; font-size: 2em; }  Automatically convert Style Sheets to inline style. 15. Send HTML email including CSS style sheet via PHP. 2. z-index ignored in newsletter. 8.NET convert external

I haven't tried this but looks like you can use something like CSS parser to get a DOM tree corresponding to your CSS. So you can do something like:

  1. Obtain cssDOM
  2. Obtain htmlDOM (JAXP)
  3. Iterate over each cssDOM element and use xpath to locate and insert the correct style in your htmlDOM.
  4. Convert htmlDOM to string.

Responsive Email CSS Inliner, Use our free CSS inliner tool to inline your styles in HTML for your email templates and to ensure they render properly in your customers email clients. Premailer is a Python library based on libxml which can analyze a HTML document and extract its CSS style sheets and then for all CSS seletors defined, it finds the DOM nodes and puts style attributes in instead.

I can't yet comment but I wrote a gist that attempted to enhance the accepted answer to handle the cascading part of cascading stylesheets.

It doesn't work perfectly but it is almost there.

CSS::Inliner, Subsequently calls the read method automatically. This method expands all relative urls, as well as fully expands the stylesheet reference within the document. Em Ji Madhu is right. You may use this website CSS Out - Remove inline CSS to remove your inline CSS for a separate stylesheet.

MyIntervals/emogrifier: Converts CSS styles into inline style , Converts CSS styles into inline style attributes in your HTML code. For example​, style="width: 100px" will be converted to width="100" . Emogrifier automatically converts the provided (X)HTML into HTML5, i.e., self-closing tags will lose  Emogrifier solves this problem by converting CSS into HTML inline style attributes in your code. How it Works. Emogrifier automagically transmogrifies your HTML by parsing your CSS and inserting your CSS definitions into tags within your HTML based on your CSS selectors.

Convert css to inline styles html online, A jQuery plugin for converting CSS styles rules into inline style attributes. tools available that can render help in automatically inlining CSS for your emails. What style will be used when there is more than one style specified for an HTML element? All the styles in a page will "cascade" into a new "virtual" style sheet by the following rules, where number one has the highest priority: Inline style (inside an HTML element) External and internal style sheets (in the head section) Browser default

inline-css, Need private packages and team management tools?Check out npm Teams ». inline-css. 2.6.3 • Public • Published 2 months ago. Readme · ExploreBETA · 7  HTML CSS, Inline CSS, Internal CSS, External CSS - 3 Ways to Style HTML with CSS Part- 1 For website development and other help, you can contact me on: Mobil

  • Similar to What tools to automatically inline CSS style to create email HTML code ? but that was not targetted at and did not yield any Java solutions
  • You're building a webmail app, right? What if someone sends something like width: expression(alert('hacked'));? Are you covering that?
  • Yes. After the conversion I will split out the names and values and then require both the names values to match a regex of safe options and put back the ones that are safe.
  • Sorry, but there is no way we will be preserving style sheets in emails for the purpose of W3C standards. Do you have a link to the standard you are referring to? @varun
  • I'm pretty sure that this does not qualify as a Java solution.
  • This an awesome solution, and worth a +1. But should be noted that selector inheritance and specifity rules are not respected!
  • Please notice that the new CSS @media rules break this solution.
  • This solution will also choke on side-sby-side tags such as h{} because the { and } will be counter as one seperator by StringTokenizer.
  • Note: Crashes on selectors with colon. I.e. "a:link {...}" will generate a$SelectorParseException
  • Nice, however it fails to put ordering rules (e.g. by priority) e.g. more specific rules should override less specific ones
  • As a side note, by changing CSSOMParser parser = new CSSOMParser(); to CSSOMParser parser = new CSSOMParser(new SACParserCSS3()); I was better able to parse CSS3.