Skip to main content

grid_holy_grail/
grid_holy_grail.rs

1// This creates a so-called "holy grail" layout using the CSS Grid layout algorithm
2// See: https://en.wikipedia.org/wiki/Holy_grail_(web_design)
3
4// NOTE: This example requires the `grid` feature flag to be enabled.
5
6#[cfg(not(feature = "grid"))]
7fn main() {
8    println!("Error: this example requires the 'grid' feature to be enabled");
9    println!("Try:");
10    println!("    cargo run --example grid_holy_grail --features grid")
11}
12
13#[cfg(feature = "grid")]
14fn default<T: Default>() -> T {
15    Default::default()
16}
17
18#[cfg(feature = "grid")]
19fn main() -> Result<(), taffy::TaffyError> {
20    use taffy::prelude::*;
21
22    let mut taffy: TaffyTree<()> = TaffyTree::new();
23
24    // Setup the grid
25    let root_style = Style {
26        display: Display::Grid,
27        size: Size { width: length(800.0), height: length(600.0) },
28        grid_template_columns: vec![length(250.0), fr(1.0), length(250.0)],
29        grid_template_rows: vec![length(150.0), fr(1.0), length(150.0)],
30        ..default()
31    };
32
33    // Define the child nodes
34    let header = taffy.new_leaf(Style { grid_row: line(1), grid_column: span(3), ..default() })?;
35    let left_sidebar = taffy.new_leaf(Style { grid_row: line(2), grid_column: line(1), ..default() })?;
36    let content_area = taffy.new_leaf(Style { grid_row: line(2), grid_column: line(2), ..default() })?;
37    let right_sidebar = taffy.new_leaf(Style { grid_row: line(2), grid_column: line(3), ..default() })?;
38    let footer = taffy.new_leaf(Style { grid_row: line(3), grid_column: span(3), ..default() })?;
39
40    // Create the container with the children
41    let root = taffy.new_with_children(root_style, &[header, left_sidebar, content_area, right_sidebar, footer])?;
42
43    // Compute layout and print result
44    taffy.compute_layout(root, Size { width: length(800.0), height: length(600.0) })?;
45    taffy.print_tree(root);
46
47    Ok(())
48}