CodeBlanks Logo Icon CodeBlanks

alignItems

Learn cross-axis alignment with alignItems.

alignItems

alignItems aligns children on the cross axis. With flexDirection: 'row' the main axis is horizontal and the cross axis is vertical; here alignItems aligns children vertically. Common values: 'flex-start' (top), 'center' (center), 'flex-end' (bottom), 'stretch' (fill the container).

The default is 'stretch'; that is why with flexDirection: 'column' children fill the container width. To equalize heights in a button bar alignItems: 'center' is common.

A centered button bar

Buttons in a bar may differ in height; alignItems: 'center' centers them all vertically. So even if one button is tall and another short, they look aligned. Combined with justifyContent: 'space-between' you get a bar where buttons hug the edges horizontally and the middle vertically.

Example: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }. This trio is very common in mobile design; it forms the basic combination for toolbars, header rows and menus.

Practice Write a centered row

Fill the empty StyleSheet.create block. Define a style named row with flexDirection: 'row', justifyContent: 'center', alignItems: 'center'. The component returns a <View style={styles.row}> containing <Text>A</Text> and <Text>B</Text>.

Starter code

App.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

export default function Row() {
  return (
    <View>
      <Text>A</Text>
      <Text>B</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  // Add the row style here
});

Sample solution

App.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

export default function Row() {
  return (
    <View style={styles.row}>
      <Text>A</Text>
      <Text>B</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  row: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }
});

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each value to its alignment

Term Meaning
'flex-start' Top alignment
'center' Middle alignment
'flex-end' Bottom alignment
'stretch' Fill the container

2 What is the default value of alignItems?

App.js
<View style={{ flexDirection: 'row' }}>
  {/* alignItems omitted */}
</View>
  • 'stretch' Correct answer
  • 'flex-start'
  • 'center'
  • 'auto'

Explanation: The default is 'stretch'; children fill the container.

3 Write the vertical centering value

Question
<View style={{ flexDirection: 'row', alignItems:____}}>
  <Text>A</Text>
  <Text>B</Text>
</View>
Answer
<View style={{ flexDirection: 'row', alignItems:'center'}}>
  <Text>A</Text>
  <Text>B</Text>
</View>

Explanation: 'center' centers children on the cross axis.

All lessons in Beginner