Skip to content

Styling Text

Styling enhances user experience by adding colors, emphasis, and other visual aids. In ratatui, the primary tool for this is the ratatui::style::Style struct.

ratatui::style::Style provides a set of methods to apply styling attributes to your text. These styles can then be applied to various text structures like Text, Span, and Line (as well as other non text structures).

Common styling attributes include:

  • Foreground and Background Colors (fg and bg)
  • Modifiers (like bold, italic, and underline)
  1. Basic Color Styling

    Setting the foreground (text color) and background:

    let styled_text = Span::styled(
    "Hello, Ratatui!",
    Style::default().fg(Color::Red).bg(Color::Yellow)
    );
  2. Using Modifiers

    Making text bold or italic:

    let bold_text = Span::styled(
    "This is bold",
    Style::default().add_modifier(Modifier::BOLD)
    );
    let italic_text = Span::styled(
    "This is italic",
    Style::default().add_modifier(Modifier::ITALIC)
    );

    You can also combine multiple modifiers:

    let bold_italic_text = Span::styled(
    "This is bold and italic",
    Style::default().add_modifier(Modifier::BOLD | Modifier::ITALIC)
    );
  3. Styling within a Line

    You can mix and match different styled spans within a single line:

    let mixed_line = Line::from(vec![
    Span::styled("This is mixed", Style::default().fg(Color::Green)),
    Span::styled("styling", Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)),
    Span::from("!"),
    ]);

This is what it would look like if you rendered a Paragraph with different styles for each line:

fn ui(_: &App, f: &mut Frame) {
let styled_text = Span::styled("Hello, Ratatui!", Style::default().fg(Color::Red).bg(Color::Yellow));
let bold_text = Span::styled("This is bold", Style::default().add_modifier(Modifier::BOLD));
let italic_text = Span::styled("This is italic", Style::default().add_modifier(Modifier::ITALIC));
let bold_italic_text =
Span::styled("This is bold and italic", Style::default().add_modifier(Modifier::BOLD | Modifier::ITALIC));
let mixed_line = vec![
Span::styled("This is mixed", Style::default().fg(Color::Green)),
Span::styled("styling", Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)),
Span::from("!"),
];
let text: Vec<Line<'_>> =
vec![styled_text.into(), bold_text.into(), italic_text.into(), bold_italic_text.into(), mixed_line.into()];
f.render_widget(Paragraph::new(text).block(Block::default().borders(Borders::ALL)), f.size());
}

Here’s the HTML representation of the above styling:

Hello, Ratatui!

This is bold

This is italic

This is bold and italic

This is mixed styling !

You can read more about the Color enum and Modifier in the reference documentation online.