tezvyn:

alignItems: Aligning Children on the Cross Axis

AI-drafted, machine-checkedSource: reactnative.devintermediate

alignItems arranges children along the cross axis of a flex container. If items flow down (column), it aligns them left/right. If they flow across (row), it aligns them top/bottom. The footgun: `alignSelf` on a child overrides this parent property.

WHY IT EXISTS In a flexible layout system, you need control over two axes: the main flow direction and the one perpendicular to it. alignItems was created to provide a simple, declarative way to manage alignment on that second, "cross" axis for all children within a container, without styling each one individually.

THE MENTAL MODEL Think of a container with flexDirection: 'column'. Your items stack vertically, so the main axis is vertical. alignItems controls their horizontal alignment on the cross axis. It's like telling all items on a string to slide to the left, right, or center of the available space. If flexDirection is 'row', the main axis is horizontal, and alignItems controls their vertical alignment.

HOW IT WORKS alignItems is a style property you set on a parent container, like a View. It accepts one of five string values. flex-start pushes children to the start of the cross axis (left for a column, top for a row). flex-end pushes them to the end. center centers them along the cross axis. stretch, the default value, makes children expand to fill the container's cross-axis dimension. baseline aligns children based on the baseline of their text content.

WHEN TO USE IT Use alignItems on a parent container whenever you want to apply a consistent alignment rule to all of its direct children. It's the standard tool for centering a group of items, left-aligning form fields in a vertical stack, or vertically centering icons and text in a header row. It simplifies layout by setting a rule on the container rather than on every child.

WHEN NOT TO USE IT Do not use alignItems when you need to align a single, specific child differently from its siblings. For that one-off case, apply the alignSelf property directly to the child component you want to target. alignSelf accepts the same values but overrides the parent's alignItems for that one element. Also, alignItems has no effect on a container with no children.

ONE CANONICAL EXAMPLE To perfectly center a button on the screen, you would create a parent View with flex: 1 (to take up all space), justifyContent: 'center' (to center vertically on the main axis), and alignItems: 'center' (to center horizontally on the cross axis). The child button inside this view will then be perfectly centered.

Read the original → reactnative.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.