ratatui

Module style

source
Expand description

style contains the primitives used to control how your user interface will look.

There are two ways to set styles:

  • Creating and using the Style struct. (e.g. Style::new().fg(Color::Red)).
  • Using style shorthands. (e.g. "hello".red()).

§Using the Style struct

This is the original approach to styling and likely the most common. This is useful when creating style variables to reuse, however the shorthands are often more convenient and readable for most use cases.

§Example

use ratatui::{
    style::{Color, Modifier, Style},
    text::Span,
};

let heading_style = Style::new()
    .fg(Color::Black)
    .bg(Color::Green)
    .add_modifier(Modifier::ITALIC | Modifier::BOLD);
let span = Span::styled("hello", heading_style);

§Using style shorthands

Originally Ratatui only had the ability to set styles using the Style struct. This is still supported, but there are now shorthands for all the styles that can be set. These save you from having to create a Style struct every time you want to set a style.

The shorthands are implemented in the Stylize trait which is automatically implemented for many types via the Styled trait. This means that you can use the shorthands on any type that implements Styled. E.g.:

  • Strings and string slices when styled return a Span
  • Spans can be styled again, which will merge the styles.
  • Many widget types can be styled directly rather than calling their style() method.

See the Stylize and Styled traits for more information.

§Example

use ratatui::{
    style::{Color, Modifier, Style, Stylize},
    text::Span,
    widgets::Paragraph,
};

assert_eq!(
    "hello".red().on_blue().bold(),
    Span::styled(
        "hello",
        Style::default()
            .fg(Color::Red)
            .bg(Color::Blue)
            .add_modifier(Modifier::BOLD)
    )
);

assert_eq!(
    Paragraph::new("hello").red().on_blue().bold(),
    Paragraph::new("hello").style(
        Style::default()
            .fg(Color::Red)
            .bg(Color::Blue)
            .add_modifier(Modifier::BOLD)
    )
);

Modules§

  • A module for defining color palettes.

Structs§

  • Modifier changes the way a piece of text is displayed.
  • Error type indicating a failure to parse a color string.
  • Style lets you control the main characteristics of the displayed elements.

Enums§

Traits§

  • A trait for objects that have a Style.
  • An extension trait for styling objects.