css-inline: High-Performance CSS Inliner for HTML
css-inline is a high-performance Python library (version 0.20.2) for inlining CSS into HTML 'style' attributes. Built on components from Mozilla's Servo project, it is significantly faster than other alternatives and is primarily designed for use cases such as preparing HTML emails or embedding HTML into third-party web pages where inline styles are a requirement. It's actively maintained with regular releases.
Warnings
- gotcha By default, `<style>` and `<link>` tags (including their contents) are removed from the resulting HTML after inlining. If you need to preserve them (e.g., for responsive email media queries), use the `keep_style_tags=True` or `keep_link_tags=True` options.
- gotcha At-rules (like `@media`, `@font-face`) cannot be inlined into `style` attributes and are removed by default. To preserve them (e.g., for responsive email layouts), set `keep_at_rules=True`.
- gotcha When inlining HTML fragments, `css-inline` automatically adds missing `<html>` and `<body>` tags to ensure the output is a valid HTML document. If you specifically need to process and return only the contents of an HTML fragment without these structural tags, consider processing and then manually stripping them, or use `inline_many_fragments` which might offer more control.
- breaking The `inline_with_options` and `inline_many_with_options` functions were removed. Users should now pass options directly as keyword arguments to the `inline()` and `inline_many()` functions, or use the `CSSInliner` class.
- breaking The arguments for `inline_many` and `inline_many_fragments` changed. They now expect a list of tuples `(html_string, options_dict)` instead of just `html_string` for each item. This allows specific options per document when processing in parallel.
- gotcha As a library for *inlining* CSS, it cannot handle pseudo-elements (`::before`, `::after`) or pseudo-classes (`:hover`, `:active`) because these CSS features cannot be represented directly as `style` attributes on HTML elements.
Install
-
pip install css-inline
Imports
- inline
from css_inline import inline
- inline_many
from css_inline import inline_many
- CSSInliner
from css_inline import CSSInliner
Quickstart
from css_inline import inline
html_content = """
<html>
<head>
<style>
h1 { color: blue; }
p { font-size: 14px; margin-bottom: 5px; }
.highlight { background-color: yellow; }
@media screen and (max-width: 600px) { p { color: #555; } }
</style>
</head>
<body>
<h1 class="highlight">Hello, World!</h1>
<p>This is a paragraph.</p>
<p style="color: green;">This paragraph has an existing inline style.</p>
</body>
</html>
"""
inlined_html = inline(html_content, keep_at_rules=True, keep_style_tags=True)
print(inlined_html)