React Native
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.
Exercise 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>.
Show example solution
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' }
});
Test yourself
-
Match each value to its alignment
- 'flex-start'
- Top alignment
- 'center'
- Middle alignment
- 'flex-end'
- Bottom alignment
- 'stretch'
- Fill the container
-
What is the default value of alignItems?
<View style={{ flexDirection: 'row' }}>
{/* alignItems omitted */}
</View>
- 'stretch'
- 'flex-start'
- 'center'
- 'auto'
Show answer
'stretch' — The default is 'stretch'; children fill the container.
-
Write the vertical centering value
<View style={{ flexDirection: 'row', alignItems:____}}>
<Text>A</Text>
<Text>B</Text>
</View>
Show answer
<View style={{ flexDirection: 'row', alignItems:'center'}}>
<Text>A</Text>
<Text>B</Text>
</View>
Next lesson: flex