Question #304EasyWidgets & UI

When should you use mainAxisAlignment and crossAxisAlignment?

#flutter#widget#layout

Answer

Overview

text
mainAxisAlignment
and
text
crossAxisAlignment
control how children are positioned within a
text
Row
or
text
Column
. The key is understanding what the main axis and cross axis are for each widget.


Axis Directions

WidgetMain AxisCross Axis
text
Column
Vertical (↕)Horizontal (↔)
text
Row
Horizontal (↔)Vertical (↕)

mainAxisAlignment — Along the Main Axis

Controls spacing/positioning of children along the primary direction.

dart
Column(
  mainAxisAlignment: MainAxisAlignment.center, // children grouped at center vertically
  children: [Text('A'), Text('B'), Text('C')],
)
ValueEffect
text
start
Pack children at the start (default)
text
end
Pack children at the end
text
center
Pack children at the center
text
spaceBetween
Equal space between children, no edge space
text
spaceAround
Equal space around children (half at edges)
text
spaceEvenly
Equal space between and at edges
dart
Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: [
    Icon(Icons.home),
    Icon(Icons.search),
    Icon(Icons.person),
  ],
)
// Result: [HOME]     [SEARCH]     [PERSON]

crossAxisAlignment — Along the Cross Axis

Controls how children are aligned perpendicular to the main axis.

dart
Row(
  crossAxisAlignment: CrossAxisAlignment.center, // children centered vertically
  children: [
    Text('Hello', style: TextStyle(fontSize: 24)),
    Text('World', style: TextStyle(fontSize: 12)),
  ],
)
ValueEffect
text
start
Align to the start of the cross axis
text
end
Align to the end of the cross axis
text
center
Center on the cross axis (default)
text
stretch
Stretch children to fill the cross axis
text
baseline
Align text baselines (use with
text
TextBaseline
)

Common Examples

dart
// Centered content in a Column
Column(
  mainAxisAlignment: MainAxisAlignment.center,   // Vertical center
  crossAxisAlignment: CrossAxisAlignment.center, // Horizontal center
  children: [
    Icon(Icons.star, size: 48),
    Text('You're a star!'),
  ],
)

// Bottom bar layout
Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly, // Spread icons evenly
  crossAxisAlignment: CrossAxisAlignment.center,    // Vertically centered
  children: [
    IconButton(icon: Icon(Icons.home), onPressed: () {}),
    IconButton(icon: Icon(Icons.search), onPressed: () {}),
    IconButton(icon: Icon(Icons.settings), onPressed: () {}),
  ],
)

When to Use What

GoalUse
Center all content
text
mainAxisAlignment: center
+
text
crossAxisAlignment: center
Space out nav bar items
text
mainAxisAlignment: spaceEvenly
or
text
spaceBetween
Stretch children to full width (in Column)
text
crossAxisAlignment: stretch
Left-align text in a Column
text
crossAxisAlignment: start
Push items to bottom of Column
text
mainAxisAlignment: end

Memory Tip:

text
main
= the direction the widget flows.
text
cross
= the other direction.