3 releases

0.0.3 May 18, 2023
0.0.2 May 18, 2023
0.0.1 May 18, 2023

#2454 in Parser implementations

48 downloads per month

LGPL-3.0-or-later

22KB
442 lines

inline-css

Inline CSS directly into your Rust code.

Example

use inline_css::css;

fn main() {
    let css = css! {
        h1 {
            color: red;
        }
    };
    
    println!("{css}");
}

Syntax issues

margin: 10em;

This doesn't work because Rust expects an exponent after the e. The workaround is to write 10m, which the macro implicitly converts to 10em.

padding: calc(10 - 1);

Unsupported, use padding: {10 - 1}; instead.

color: #0000ef;

Impossible to parse, use color: #0xff00ff; instead.

color: #0x0ff;

Is interpreted as color: #0x0000ff;, please use color: #0x00ffff; instead.

TODO

  • Documentation
  • Parse h1::after {}

lib.rs:

Embed CSS directly into your Rust code.

Example

use inline_css::*;

let x = 42;

let css = css! {
    h1 {
        color: red;
        background-color: #0x00ffff; // not #00ffff
        padding: 10px;
        margin-left: 10m; // not 10em
        margin-right: -4%;
    }
};

println!("{css}");

How to use

Use the css! {..} macro to embed CSS directly into your Rust code. During the compile-time of your Rust program, the content inside of your css! invocations will be checked and converted to an instance of CSS. This makes sure that all invocations of the css! macro are guaranteed to be valid CSS at runtime.

Integration with inline-xml

inline-css implements ToXml for CSS for integration with inline-xml.

Example

extern crate inline_xml;
use inline_xml::xml;
use inline_css::css;

let css = css! {
    h1 {
        color: red;
    }
};

let html = xml! {
    <html>
        <head>
            <style>{css}</style>
        </head>
        <body>
            <h1>Hello World</h1>
        </body>
    </html>
};

Variants

There are 3 macros:

css!

Parse an entire snippet of CSS.

use inline_css::*;

let rule: CSS = css! {
    h1 {
        color: red;
    }

    .button {
        color: blue;
    }

    #text {
        color: green;
    }
};

css_rule!

Parse a single CSS Rule.

use inline_css::*;

let rule: Rule = css_rule! {
    h1 {
        color: red;
    }
};

css_value!

Parse a CSS Value.

use inline_css::*;

let value: Value = css_value! { 10px };

Dynamic Data

You can include dynamically-generated data into the css! macro invocation.

Only types implementing Into<Value> are supported.

Example

use inline_css::*;

let x = 42;
let css = css! {
    h1 {
        attr: {x + 1};
    }
};

Dependencies

~1.5MB
~37K SLoC