Sub topic 5
Aligning children with MainAxisAlignment and CrossAxisAlignment
This chapter assumes you know Dart basics, can write a StatelessWidget with a build method, and can run a Flutter app. It also assumes you have met the main axis and cross axis of Row and Column in the previous chapter. Here you will learn the two properties that position children along those axes, and the errors that appear when they don't behave as you expect.
What alignment controls
A Row or Column first lays out its children, then decides where to put them. Two properties control that placement:
mainAxisAlignmentplaces children along the main axis. That is horizontal in aRowand vertical in aColumn.crossAxisAlignmentplaces children along the cross axis. That is vertical in aRowand horizontal in aColumn.
Alignment only distributes free space, meaning the room left over after the children have taken their own size. If the children already fill the main axis, mainAxisAlignment has nothing to distribute and appears to do nothing. This is the most common reason alignment seems broken.
The diagram shows an important difference. mainAxisAlignment positions the children as a group, using the total leftover space. crossAxisAlignment positions each child individually, because each child has its own size on the cross axis.
MainAxisAlignment values
MainAxisAlignment has six values. Assume a Row that is 300 pixels wide with three children of 50 pixels each. That leaves 150 pixels of free space.
| Value | Where the free space goes | Result in the example |
|---|---|---|
| `start` | After the last child | Children packed at the left |
| `end` | Before the first child | Children packed at the right |
| `center` | Half before, half after | 75 px on each side |
| `spaceBetween` | Equally between children | 75 px gaps, none at the edges |
| `spaceAround` | Around each child, with edge gaps half the size of inner gaps | 25 px at each edge, 50 px between |
| `spaceEvenly` | Equally between children and at the edges | 37.5 px everywhere |
The default is start. The numbers for spaceAround come from giving each child half a gap on each side: 150 divided by three children gives 50 px per child, so 25 px on each side of each child.
This example from the topic shows spaceBetween in a Row:
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Icon(Icons.star),
const Text('Rating'),
const Text('4.8'),
],
)The icon sits at the left edge, '4.8' at the right edge, and 'Rating' is placed so the two gaps are equal. Note that this works only if the Row is wider than its children. A Row inside a Column with default settings receives the full width of the screen, so it works. A Row inside another widget that shrinks it to its content would not show any spacing.
CrossAxisAlignment values
CrossAxisAlignment has five values:
| Value | Behavior |
|---|---|
| `start` | Each child is placed at the start of the cross axis (top in a `Row`, left in a `Column`) |
| `end` | Each child is placed at the end of the cross axis |
| `center` | Each child is centered. This is the default |
| `stretch` | Each child is forced to fill the cross axis |
| `baseline` | Children are lined up by their text baseline. Works only in a `Row` and needs `textBaseline` |
The default is center, which is why children in a Row are vertically centered without you asking.
This example uses start in a Column:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Title'),
const SizedBox(height: 8),
const Text('Subtitle'),
],
)Without crossAxisAlignment.start, the two text widgets would be centered horizontally relative to the widest child. With it, both are flush left.
How stretch works
stretch is different from the others because it changes constraints, not just position. A Column normally gives each child a horizontal range from zero up to its own width. With stretch, it gives each child a tight width equal to the Column's width. A Container with a color then fills the whole width:
import 'package:flutter/material.dart';
class StretchDemo extends StatelessWidget {
const StretchDemo({super.key});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(height: 40, color: Colors.blue),
const SizedBox(height: 8),
Container(height: 40, color: Colors.red),
],
);
}
}Both bars span the full width without any width value. Without stretch, a Container with no child and no width would also expand, but a Container with a Text child would shrink to the text. stretch forces the wider size.
The baseline gotcha
CrossAxisAlignment.baseline aligns text in different sizes along the line the letters sit on. It requires textBaseline, and Flutter asserts if you omit it:
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: const [
Text('Total', style: TextStyle(fontSize: 14)),
SizedBox(width: 8),
Text('$42', style: TextStyle(fontSize: 32)),
],
)With center, the small label would float at mid-height of the large number. With baseline, both texts rest on the same line, which looks correct for price displays.
Alignment and the size of the parent
Cross axis alignment is relative to the height of the Row (or the width of a Column). That size is the largest child on the cross axis, unless the parent forces something bigger. So in a Row whose tallest child is 100 px, crossAxisAlignment.end pushes shorter children down to that 100 px line. If every child is the same height, all cross axis values look the same except stretch, because there is no free space.
To see the effect, wrap the Row in a SizedBox with a fixed height:
SizedBox(
height: 120,
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Container(width: 40, height: 40, color: Colors.blue),
Container(width: 40, height: 80, color: Colors.green),
],
),
)The SizedBox gives the Row a tight height of 120. Both boxes sit on the bottom edge of that area.
The main axis behaves similarly. A Column takes all available height by default, because mainAxisSize is MainAxisSize.max. If you set mainAxisSize: MainAxisSize.min, the Column shrinks to fit its children and mainAxisAlignment has no free space left. The next chapter covers MainAxisSize in detail, but keep it in mind when alignment seems to have no effect.
Alignment when children use Expanded
An Expanded child takes all remaining main axis space. If any child in a Row is Expanded, there is no free space left, so mainAxisAlignment has no visible effect. The cross axis is still affected:
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.info),
const SizedBox(width: 8),
Expanded(
child: Text(
'A long message that wraps over several lines in a narrow screen.',
),
),
],
)Here crossAxisAlignment.start keeps the icon at the top of the paragraph instead of centering it against several lines of text. This pattern is common in list items and banners.
Common errors
- No visible change from
mainAxisAlignment. The children fill the main axis, anExpandedchild consumed the space, ormainAxisSizeismin. Check how much free space exists. crossAxisAlignment.stretchin an unbounded direction. AColumninside a horizontally scrolling widget has an unbounded cross axis, sostretchcannot make children infinitely wide. Flutter reports a layout error. Give theColumna bounded width.- Missing
textBaseline. Usingbaselinewithout it fails an assertion. - Using
baselinein aColumn. Baseline alignment is meaningful only when the cross axis is vertical, which is in aRow. - Confusing the axes.
MainAxisAlignment.centercenters vertically in aColumnbut horizontally in aRow. If your result is off by 90 degrees, swap which property you are setting.
Summary of decisions
- To spread items along the line, use
spaceBetween,spaceAround, orspaceEvenly. - To group items at one end or the middle, use
start,end, orcenter. - To align items of different size across the line, use
crossAxisAlignment. - To make items fill the cross axis, use
stretch. - To align text of different sizes, use
baselinewithtextBaseline.
Exercise
A Row is 300 px wide and contains three 50 px boxes. You set mainAxisAlignment to MainAxisAlignment.spaceEvenly. How wide is each gap, including the gaps at the left and right edges? Then you wrap the middle box in Expanded. What happens to the gaps?
Show answer
Free space is 300 - 150 = 150 px. spaceEvenly uses four gaps (two edges and two between children), so each is 150 / 4 = 37.5 px. After wrapping the middle box in Expanded, that box grows to take all free space (to 200 px wide). No free space remains, so every gap becomes 0 and mainAxisAlignment has no visible effect.
Exercise
A list item has an Icon followed by an Expanded Text that wraps to three lines. By default the icon is centered vertically against the text. Which property and value place the icon at the top, and why does mainAxisAlignment not help?
Show answer
Set crossAxisAlignment: CrossAxisAlignment.start on the Row. The icon's position relative to the text is a cross axis matter, because the Row's cross axis is vertical. mainAxisAlignment controls horizontal placement in a Row, and the Expanded child already uses up all horizontal free space.