A crate for inlining CSS into HTML documents. It is built with Mozilla's Servo project components.
When you send HTML emails, you need to use "style" attributes instead of "style" tags. For example, this HTML:
html
<html>
<head>
<title>Test</title>
<style>h1 { color:blue; }</style>
</head>
<body>
<h1>Big Text</h1>
</body>
</html>
Will be turned into this:
html
<html>
<head><title>Test</title></head>
<body>
<h1 style="color:blue;">Big Text</h1>
</body>
</html>
To use it in your project add the following line to your dependencies section in the project's Cargo.toml file:
toml
css-inline = "0.8"
Minimum Supported Rust Version is 1.54.
```rust const HTML: &str = r#"
fn main() -> Result<(), cssinline::InlineError> { let inlined = cssinline::inline(HTML)?; // Do something with inlined HTML, e.g. send an email Ok(()) } ```
css-inline can be configured by using CSSInliner::options() that implements the Builder pattern:
```rust const HTML: &str = "...";
fn main() -> Result<(), cssinline::InlineError> { let inliner = cssinline::CSSInliner::options() .loadremotestylesheets(false) .build(); let inlined = inliner.inline(HTML); // Do something with inlined HTML, e.g. send an email Ok(()) } ```
inline_style_tags. Whether to inline CSS from "style" tags. Default: trueremove_style_tags. Remove "style" tags after inlining. Default: falsebase_url. Base URL to resolve relative URLs. Default: Noneload_remote_stylesheets. Whether remote stylesheets should be loaded or not. Default: trueextra_css. Additional CSS to inline. Default: NoneIf you'd like to skip CSS inlining for an HTML tag, add data-css-inline="ignore" attribute to it:
html
<head>
<title>Test</title>
<style>h1 { color:blue; }</style>
</head>
<body>
<!-- The tag below won't receive additional styles -->
<h1 data-css-inline="ignore">Big Text</h1>
</body>
</html>
This attribute also allows you to skip link and style tags:
html
<head>
<title>Test</title>
<!-- Styles below are ignored -->
<style data-css-inline="ignore">h1 { color:blue; }</style>
</head>
<body>
<h1>Big Text</h1>
</body>
</html>
There are bindings for Python and WebAssembly in the bindings directory.
css-inline provides a command-line interface:
```text css-inline --help
css-inline inlines CSS into HTML documents.
USAGE: css-inline [OPTIONS] [PATH ...] command | css-inline [OPTIONS]
ARGS:
OPTIONS:
--inline-style-tags
Whether to inline CSS from "style" tags. The default
value is true. To disable inlining from "style" tags
use --inline-style-tags=false.
--remove-style-tags
Remove "style" tags after inlining.
--base-url
Used for loading external stylesheets via relative URLs.
--load-remote-stylesheets
Whether remote stylesheets should be loaded or not.
--extra-css
Additional CSS to inline.
```
If you want to know how this library was created & how it works internally, you could take a look at these articles:
If you have anything to discuss regarding this library, please, join our gitter!