grid/grid.rs
1//! Demonstrates how CSS Grid layout can be used to lay items out in a 2D grid
2use bevy::{color::palettes::css::*, prelude::*};
3
4fn main() {
5 App::new()
6 .add_plugins(DefaultPlugins.set(WindowPlugin {
7 primary_window: Some(Window {
8 resolution: (800, 600).into(),
9 title: "Bevy CSS Grid Layout Example".to_string(),
10 ..default()
11 }),
12 ..default()
13 }))
14 .add_systems(Startup, spawn_layout)
15 .run();
16}
17
18fn spawn_layout(mut commands: Commands, asset_server: Res<AssetServer>) {
19 let font = asset_server.load("fonts/FiraSans-Bold.ttf");
20 commands.spawn(Camera2d);
21
22 // Top-level grid (app frame)
23 commands
24 .spawn((
25 Node {
26 // Use the CSS Grid algorithm for laying out this node
27 display: Display::Grid,
28 // Make node fill the entirety of its parent (in this case the window)
29 width: percent(100),
30 height: percent(100),
31 // Set the grid to have 2 columns with sizes [min-content, minmax(0, 1fr)]
32 // - The first column will size to the size of its contents
33 // - The second column will take up the remaining available space
34 grid_template_columns: vec![GridTrack::min_content(), GridTrack::flex(1.0)],
35 // Set the grid to have 3 rows with sizes [auto, minmax(0, 1fr), 20px]
36 // - The first row will size to the size of its contents
37 // - The second row take up remaining available space (after rows 1 and 3 have both been sized)
38 // - The third row will be exactly 20px high
39 grid_template_rows: vec![
40 GridTrack::auto(),
41 GridTrack::flex(1.0),
42 GridTrack::px(20.),
43 ],
44 ..default()
45 },
46 BackgroundColor(Color::WHITE),
47 ))
48 .with_children(|builder| {
49 // Header
50 builder
51 .spawn(
52 Node {
53 display: Display::Grid,
54 // Make this node span two grid columns so that it takes up the entire top tow
55 grid_column: GridPlacement::span(2),
56 padding: UiRect::all(px(6)),
57 ..default()
58 },
59 )
60 .with_children(|builder| {
61 spawn_nested_text_bundle(builder, font.clone(), "Bevy CSS Grid Layout Example");
62 });
63
64 // Main content grid (auto placed in row 2, column 1)
65 builder
66 .spawn((
67 Node {
68 // Make the height of the node fill its parent
69 height: percent(100),
70 // Make the grid have a 1:1 aspect ratio meaning it will scale as an exact square
71 // As the height is set explicitly, this means the width will adjust to match the height
72 aspect_ratio: Some(1.0),
73 // Use grid layout for this node
74 display: Display::Grid,
75 // Add 24px of padding around the grid
76 padding: UiRect::all(px(24)),
77 // Set the grid to have 4 columns all with sizes minmax(0, 1fr)
78 // This creates 4 exactly evenly sized columns
79 grid_template_columns: RepeatedGridTrack::flex(4, 1.0),
80 // Set the grid to have 4 rows all with sizes minmax(0, 1fr)
81 // This creates 4 exactly evenly sized rows
82 grid_template_rows: RepeatedGridTrack::flex(4, 1.0),
83 // Set a 12px gap/gutter between rows and columns
84 row_gap: px(12),
85 column_gap: px(12),
86 ..default()
87 },
88 BackgroundColor(Color::srgb(0.25, 0.25, 0.25)),
89 ))
90 .with_children(|builder| {
91 // Note there is no need to specify the position for each grid item. Grid items that are
92 // not given an explicit position will be automatically positioned into the next available
93 // grid cell. The order in which this is performed can be controlled using the grid_auto_flow
94 // style property.
95
96 item_rect(builder, ORANGE);
97 item_rect(builder, BISQUE);
98 item_rect(builder, BLUE);
99 item_rect(builder, CRIMSON);
100 item_rect(builder, AQUA);
101 item_rect(builder, ORANGE_RED);
102 item_rect(builder, DARK_GREEN);
103 item_rect(builder, FUCHSIA);
104 item_rect(builder, TEAL);
105 item_rect(builder, ALICE_BLUE);
106 item_rect(builder, CRIMSON);
107 item_rect(builder, ANTIQUE_WHITE);
108 item_rect(builder, YELLOW);
109 item_rect(builder, DEEP_PINK);
110 item_rect(builder, YELLOW_GREEN);
111 item_rect(builder, SALMON);
112 });
113
114 // Right side bar (auto placed in row 2, column 2)
115 builder
116 .spawn((
117 Node {
118 display: Display::Grid,
119 // Align content towards the start (top) in the vertical axis
120 align_items: AlignItems::Start,
121 // Align content towards the center in the horizontal axis
122 justify_items: JustifyItems::Center,
123 // Add 10px padding
124 padding: UiRect::all(px(10)),
125 // Add an fr track to take up all the available space at the bottom of the column so that the text nodes
126 // can be top-aligned. Normally you'd use flexbox for this, but this is the CSS Grid example so we're using grid.
127 grid_template_rows: vec![GridTrack::auto(), GridTrack::auto(), GridTrack::fr(1.0)],
128 // Add a 10px gap between rows
129 row_gap: px(10),
130 ..default()
131 },
132 BackgroundColor(BLACK.into()),
133 ))
134 .with_children(|builder| {
135 builder.spawn((Text::new("Sidebar"),
136 TextFont {
137 font: font.clone(),
138 ..default()
139 },
140 ));
141 builder.spawn((Text::new("A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely."),
142 TextFont {
143 font: font.clone(),
144 font_size: 13.0,
145 ..default()
146 },
147 ));
148 builder.spawn(Node::default());
149 });
150
151 // Footer / status bar
152 builder.spawn((
153 Node {
154 // Make this node span two grid column so that it takes up the entire bottom row
155 grid_column: GridPlacement::span(2),
156 ..default()
157 },
158 BackgroundColor(WHITE.into()),
159 ));
160
161 // Modal (absolutely positioned on top of content - currently hidden: to view it, change its visibility)
162 builder.spawn((
163 Node {
164 position_type: PositionType::Absolute,
165 margin: UiRect {
166 top: px(100),
167 bottom: auto(),
168 left: auto(),
169 right: auto(),
170 },
171 width: percent(60),
172 height: px(300),
173 max_width: px(600),
174 ..default()
175 },
176 Visibility::Hidden,
177 BackgroundColor(Color::WHITE.with_alpha(0.8)),
178 ));
179 });
180}
181
182/// Create a colored rectangle node. The node has size as it is assumed that it will be
183/// spawned as a child of a Grid container with `AlignItems::Stretch` and `JustifyItems::Stretch`
184/// which will allow it to take its size from the size of the grid area it occupies.
185fn item_rect(builder: &mut ChildSpawnerCommands, color: Srgba) {
186 builder
187 .spawn((
188 Node {
189 display: Display::Grid,
190 padding: UiRect::all(px(3)),
191 ..default()
192 },
193 BackgroundColor(BLACK.into()),
194 ))
195 .with_children(|builder| {
196 builder.spawn((Node::default(), BackgroundColor(color.into())));
197 });
198}
199
200fn spawn_nested_text_bundle(builder: &mut ChildSpawnerCommands, font: Handle<Font>, text: &str) {
201 builder.spawn((
202 Text::new(text),
203 TextFont { font, ..default() },
204 TextColor::BLACK,
205 ));
206}