Vertically centering text over images in react native with flexbox

Mike Heavers
2 min readMar 24, 2017

--

Vertical and horizontal centering is one of those things that always comes up in design, and luckily in the past couple of years we’ve started to get better solves for it.

In web, a common practice for me was to use absolute positioning on the text, with a

left: 50%, top: 50%, transform: translate(-50%,-50%)

style to get it to center over the image.

Unless you’re using one of the recent versions of react native, however, you don’t have access to percentages, and chances are you’re using flexbox as a default for layout. Here’s a simple alternative:

<View
style={styles.container}
>
<Image
source={{uri: 'https://images.unsplash.com/photo-1424819827928-55f0c8497861?fit=crop&w=600&h=600'}}
style={styles.image}
>
<Text
style={styles.paragraph}
>
TITLE
</Text>
</Image>
</View >
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'stretch',
justifyContent: 'center',
},
image: {
flexGrow:1,
height:null,
width:null,
alignItems: 'center',
justifyContent:'center',
},
paragraph: {
textAlign: 'center',
},
});

In React Native, an image component can encapsulate a text component, so there’s no need to establish a z index. If you don’t want to have to worry about the dimensions of your image, you can specify flexGrow, so that it fills its container, and null out the height and width, so that the encapsulated text component can align properly to the center.

If you’d like to see a live example, check out the super useful new Sketch playground utility from Exponent. It’s like CodePen for React Native and makes it super easy to test simple sketches out on device.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Mike Heavers
Mike Heavers

Written by Mike Heavers

Design Technologist, Future Products @ Mozilla

Responses (8)

Write a response