Package: css-inline
css_inlinecss_inlineis a high-performance library for inlining CSS into HTML 'style' attributes.This library is designed for scenarios such as preparing HTML emails or embedding HTML into third-party web pages.For instance, the library transforms HTML like this:<html><head><style>h1{color:blue;}</style></head><body><h1>Big Text</h1></body></html>into:<html><head></head><body><h1style="color:blue;">Big Text</h1></body></html>Uses reliable components from Mozilla's Servo project10-400x faster than alternativesInlines CSS fromstyleandlinktagsRemovesstyleandlinktagsResolves external stylesheets (including local files)Can process multiple documents in parallelWorks on Linux, Windows, and macOSSupports HTML5 & CSS3Tested on CPython 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and PyPy 3.7, 3.8, 3.9, 3.10.PlaygroundIf you'd like to trycss-inline, you can check the WebAssembly-poweredplaygroundto see the results instantly.InstallationInstall withpip:pipinstallcss_inlinePre-compiled wheels are available for most popular platforms.
If not available for your platform, a Rust compiler will be needed to build this package from source. Rust version 1.65 or higher is required.Usageimportcss_inlineHTML="""<html><head><style>h1 { color:blue; }</style></head><body><h1>Big Text</h1></body></html>"""inlined=css_inline.inline(HTML)# HTML becomes this:## <html># <head>#    <style>h1 { color:blue; }</style># </head># <body>#     <h1 style="color:blue;">Big Text</h1># </body># </html>When there is a need to inline multiple HTML documents simultaneously,css_inlineoffers theinline_manyfunction.
This feature allows for concurrent processing of several inputs, significantly improving performance when dealing with a large number of documents.importcss_inlinecss_inline.inline_many(["<...>","<...>"])Under the hood,inline_many, spawns threads at the Rust layer to handle the parallel processing of inputs.
This results in faster execution times compared to employing parallel processing techniques at the Python level.Note: To fully benefit frominline_many, you should run your application on a multicore machine.ConfigurationFor configuration options use theCSSInlinerclass:importcss_inlineinliner=css_inline.CSSInliner(keep_style_tags=True)inliner.inline("...")inline_style_tags. Specifies whether to inline CSS from "style" tags. Default:Truekeep_style_tags. Specifies whether to keep "style" tags after inlining. Default:Falsekeep_link_tags. Specifies whether to keep "link" tags after inlining. Default:Falsebase_url. The base URL used to resolve relative URLs. If you'd like to load stylesheets from your filesystem, use thefile://scheme. Default:Noneload_remote_stylesheets. Specifies whether remote stylesheets should be loaded. Default:Trueextra_css. Extra CSS to be inlined. Default:Nonepreallocate_node_capacity.Advanced. Preallocates capacity for HTML nodes during parsing. This can improve performance when you have an estimate of the number of nodes in your HTML document. Default:32You can also skip CSS inlining for an HTML tag by adding thedata-css-inline="ignore"attribute to it:<head><style>h1{color:blue;}</style></head><body><!-- The tag below won't receive additional styles --><h1data-css-inline="ignore">Big Text</h1></body>Thedata-css-inline="ignore"attribute also allows you to skiplinkandstyletags:<head><!-- Styles below are ignored --><styledata-css-inline="ignore">h1{color:blue;}</style></head><body><h1>Big Text</h1></body>Alternatively, you may keepstylefrom being removed by using thedata-css-inline="keep"attribute.
This is useful if you want to keep@mediaqueries for responsive emails in separatestyletags:<head><!-- Styles below are not removed --><styledata-css-inline="keep">h1{color:blue;}</style></head><body><h1>Big Text</h1></body>Such tags will be kept in the resulting HTML even if thekeep_style_tagsoption is set tofalse.If you'd like to load stylesheets from your filesystem, use thefile://scheme:importcss_inline# styles/email is relative to the current directoryinliner=css_inline.CSSInliner(base_url="file://styles/email/")inliner.inline("...")XHTML compatibilityIf you'd like to work around some XHTML compatibility issues like closing empty tags (<hr>vs.<hr/>), you can use the following snippet that involveslxml:importcss_inlinefromlxmlimporthtml,etreedocument="..."# Your HTML documentinlined=css_inline.inline(document)tree=html.fromstring(inlined)inlined=etree.tostring(tree).decode(encoding="utf-8")Performancecss-inlineis powered by efficient tooling from Mozilla's Servo project and significantly outperforms other Python alternatives in terms of speed.
Most of the time it achieves over a10xspeed advantage compared to the next fastest alternative.Here is the performance comparison:Sizecss_inline 0.13.0premailer 3.10.0toronado 0.1.0inlinestyler 0.2.5pynliner 0.8.0Basic230 B6.54 µs126.95 µs (19.41x)653.12 µs (99.85x)1.02 ms (157.14x)1.17ms (179.91x)Realistic-18.58 KB133.87 µs1.41 ms (10.60x)15.85 ms (118.39x)26.48 ms (197.86x)51.56 ms (385.18x)Realistic-24.3 KB85.41 µs2.65 ms (31.09x)ERROR17.68 ms (207.07x)ERRORGitHub page1.81 MB229.02 ms24.73 s (108.02x)ERRORERRORERRORThe "Basic" case was obtained from benchmarking the example from the Usage section.
Note that thetoronado,inlinestylerandpynlinerlibraries both encountered errors when used to inline CSS in the last scenario.The benchmarking code is available in thebenches/bench.pyfile. The benchmarks were conducted using the stablerustc 1.75.0on Python3.11.7.Comparison with other librariesBesides performance,css-inlinediffers from other Python libraries for CSS inlining.Generally supports more CSS features than other libraries (for example,toronadoandpynlinerdo not support pseudo-elements);It has fewer configuration options and not as flexible aspremailer;Works on fewer platforms than LXML-based libraries (premailer,inlinestyler,toronado, and optionallypynliner);Does not have debug logs yet;Supports only HTML 5.Further readingIf you want to know how this library was created & how it works internally, you could take a look at these articles:Rust cratePython bindingsLicenseThis project is licensed under the terms of theMIT license.