CSS Styling

Class List Shortcuts

You can already do basic styling by accessing your elements style property (MDN doc, web-sys doc).

You can also already do CSS styling by setting classnames for your elements with the classList (MDN doc, web-sys doc)

#![allow(unused)]
fn main() {
async fn div_with_class() {
    let div = Div::new();
    div.class_list().add_1("my-container").expect("?!?!");
    div.render(NoChild).await;
}
}

For extra convenience, Async UI provides a few traits to make styling code a bit less verbose.

ShortcutClassList

#![allow(unused)]
fn main() {
use async_ui_web::shortcut_traits::ShortcutClassList; // 👈 new import!
async fn div_with_class_2() {
    let div = Div::new();

    // 👇 `add_class` provided by the trait
    div.add_class("my-container");
    // 👇 `add_classes` for multiple classes
    div.add_classes(["my-class", "another-class"]);

    div.render(NoChild).await;
}
}

There are a few more methods available. View the documentation here.

ShortcutClassListBuilder

#![allow(unused)]
fn main() {
use async_ui_web::shortcut_traits::ShortcutClassListBuilder; // 👈 new import!
async fn div_with_class_3() {
    Div::new()
        // 👇 add classes without putting `Div` in a variable
        .with_classes(["my-class", "another-class"])
        .render(NoChild)
        .await;
}
}

View the documentation here.

Linking CSS

You can already add your CSS content by either

  • linking it in your index.html (with a <link /> tag), or
  • constructing a <style> element with Async UI.

Async UI provide an extra mechanism that let you write your CSS in Rust file.

#![allow(unused)]
fn main() {
mod style {
    // 👇 Write our CSS here!
    async_ui_web::css!(
        "
.my-class {
	border: 2px solid red;
}
/* Supports any selector */
.flex.my-class:not(:hover) {
	background-color: green;
}
		"
    );
}
async fn div_with_style() {
    Div::new()
        // 👇 the `style::my_class` constant is generated by the macro
        .with_class(style::my_class)
        .render(NoChild)
        .await;
}
}

With this method, you don't have to worry about linking the CSS - it is done automatically by the macro.

The macro will add random postfix to your CSS class names so that you don't have to worry about name collision.

The macro expose those postfixed class names as Rust &str constants you can use.