inline adds missing html, head and body tags, so the output is a complete HTML document.
To inline CSS into an HTML fragment, use inline_fragment(html, css). Both arguments are required; css holds the stylesheet to apply. The output stays a fragment: no <html>, <head> or <body> wrapper. Use inline for full documents:
To inline many documents at once, use inline_many or inline_many_fragments.
Both process inputs in parallel and return a list of strings in input order.
inline_many_fragments pairs htmls[i] with css[i].
Warning: if the lists differ in length, inline_many_fragments silently drops the extra items from the longer list.
CSSInliner has the same two methods.
inline_many processes inputs in parallel on a Rust thread pool (Rayon), so you don't need multiprocessing.
The speedup scales with the number of CPU cores.
inline_style_tags. Inline CSS from style tags. Default: True
keep_style_tags. Keep style tags after inlining. Default: False
keep_link_tags. Keep link tags after inlining. Default: False
keep_at_rules. Keep at-rules (starting with @) after inlining. Errors in fragment inlining. Default: False
minify_css. Remove trailing semicolons and spaces between properties and values. Default: False
base_url. Base URL for resolving relative URLs. Use the file:// scheme to load stylesheets from the filesystem. Default: None
load_remote_stylesheets. Load stylesheets from link tags, over the network or from file:// paths. Default: True
cache. Cache for external stylesheets, for example StylesheetCache(size=5). Default: None
extra_css. Extra CSS to inline. Default: None
preallocate_node_capacity. Advanced. Number of HTML nodes to preallocate during parsing. Set it to your expected node count to avoid reallocations. Default: 32
remove_inlined_selectors. Remove inlined selectors from <style> blocks. Default: False
apply_width_attributes. Add width HTML attributes from CSS width properties on supported elements (table, td, th, img). Default: False
apply_height_attributes. Add height HTML attributes from CSS height properties on supported elements (table, td, th, img). Default: False
resolve_css_variables. Replace var() references with the values of the custom properties they refer to and drop the --* declarations. Default: False
media_type. Inline rules from @media blocks whose query lists this media type or all, e.g. @media print or @media screen, print for print. Queries with media features, such as print and (min-width: 600px), never apply. An inlined block is not kept as an at-rule. Ignored when keep_at_rules is enabled and inline_style_tags is disabled. Default: None
keep_classes. Keep class attributes in the output. When disabled, class selectors in kept <style> blocks and at-rules match nothing. Default: True
remove_unused_at_rules. Remove rules that match no element from kept at-rules (@media, @supports, ...), along with blocks left empty. Needs keep_at_rules or remove_inlined_selectors. Matching ignores :hover, ::before and similar. This also removes rules that target markup injected by an email client (e.g. Gmail's u ~ div .x). Default: False
To skip CSS inlining for an HTML tag, add the data-css-inline="ignore" attribute:
<head>
<style>h1 { color:blue; }</style>
</head>
<body>
<!-- The tag below won't receive additional styles -->
<h1 data-css-inline="ignore">Big Text</h1>
</body>
The same attribute on a link or style tag makes the inliner skip that stylesheet:
To keep a style tag in the output, add data-css-inline="keep".
Use it for @media queries in responsive emails.
The tag stays even with keep_style_tags=False.
<head>
<!-- Styles below are not removed -->
<style data-css-inline="keep">h1 { color:blue; }</style>
</head>
<body>
<h1>Big Text</h1>
</body>
At-rules can't go into style attributes, so the inliner removes them by default.
Set keep_at_rules=True to keep them, for example @media queries for responsive emails, in a style tag while inlining everything else.
The tag stays even with keep_style_tags=False.
<head>
<!-- With keep_at_rules=True, "color: blue" goes into <h1> and @media stays in <style> -->
<style>h1 { color: blue; } @media (max-width: 600px) { h1 { font-size: 18px; } }</style>
</head>
<body>
<h1>Big Text</h1>
</body>
minify_css=True removes trailing semicolons and spaces between properties and values in inlined styles.
<head>
<!-- With minify_css=True, the <h1> will have `style="color:blue;font-weight:bold"` -->
<style>h1 { color: blue; font-weight: bold; }</style>
</head>
<body>
<h1>Big Text</h1>
</body>
To load stylesheets from the filesystem, use the file:// scheme.
Standard URL parsing reads file://styles/email/ as host styles and path /email/.
css-inline deviates from the standard here: for a file:// URL with a host, it drops the file:// prefix and treats styles/email/ as a path relative to the current directory.
With either form, <link href="main.css"> resolves against the base, so keep the trailing slash: without it, main.css replaces the last segment (styles/main.css).
import css_inline
# Absolute directory: three slashes
inliner = css_inline.CSSInliner(base_url="file:///srv/app/styles/email/")
inliner.inline("...")
# Relative to the current directory: two slashes
inliner = css_inline.CSSInliner(base_url="file://styles/email/")
inliner.inline("...")
To avoid repeated network requests, cache external stylesheets:
size is the maximum number of stylesheets in the cache and must be greater than zero; otherwise StylesheetCache raises InlineError. When it is full, the least recently used entry is evicted. Caching is off by default.
Errors
Inlining raises css_inline.InlineError, a ValueError subclass, when a stylesheet fails to load (missing file, network error) or to parse.
An invalid base_url raises a plain ValueError.
css-inline outputs HTML5, so void tags stay unclosed (<hr>, not <hr/>). For XHTML output, re-serialize with lxml:
import css_inline
from lxml import html, etree
document = "..." # Your HTML document
inlined = css_inline.inline(document)
tree = html.fromstring(inlined)
inlined = etree.tostring(tree).decode(encoding="utf-8")
Performance
css-inline is 18x to 1115x faster than the next fastest Python inliner, premailer, on the inputs below:
Size
css_inline 0.23.1
premailer 3.10.0
toronado 0.1.0
pynliner 0.8.0
Basic
230 B
4.10 µs
111.34 µs (27.15x)
633.87 µs (154.58x)
1.08 ms (263.88x)
Realistic-1
8.58 KB
71.52 µs
1.31 ms (18.26x)
14.30 ms (200.02x)
15.21 ms (212.69x)
Realistic-2
4.30 KB
40.38 µs
1.67 ms (41.33x)
ERROR
ERROR
GitHub page
1.81 MB
11.22 ms
12.51 s (1114.78x)
ERROR
ERROR
toronado and pynliner fail on Realistic-2 and the GitHub page because those inputs contain CSS they do not support: toronado raises ExpressionError: Pseudo-elements are not supported., pynliner raises Exception: No match was found. We're done or something is broken.
inlinestyler 0.2.5 is not in the table: it crashes with current lxml ('CSSSelector' object has no attribute 'evaluate').
Inputs live in benchmarks/benchmarks.json: Basic is simple, Realistic-1 is big_email_1, Realistic-2 is big_email_2, GitHub page is big_page.
Benchmark code: benches/bench.py (pytest-benchmark, mean time). Environment: rustc 1.99 (stable), Python 3.14.5, Ryzen 9 9950X.
Comparison with other libraries
Compared to other Python inliners, css-inline:
Supports more CSS features. For example, toronado and pynliner don't support pseudo-elements.