Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Text component will not center inside a View component

Hi I think this should be simple, but I cannot get it to work. Seems like no matter what I do, I cannot get the text component to center horizontally inside the view. I have tried using alignItems:center, justifyContent:center, alignSelf:center, textAlign:center... nothing works. I can get it to center vertically, but not horizontally. Whyyyyy dear lord?

<Animated.View style={[styles.titleContainer]}>
    <Text style={styles.title}>App logo here</Text>
</Animated.View>

How can I get the text to center both vertically and horizontally?

Here is my CSS:

titleContainer: {
    flex: 1,
    marginTop:30,
    marginBottom:30,
    justifyContent:'center'
},
title:{
    color:'white',
    textAlign:'center',
    alignSelf:'center'
},

This is my result:

enter image description here

like image 935
JackKalish Avatar asked Nov 02 '15 17:11

JackKalish


People also ask

How do you center text in a view React Native?

To center text with React Native, we can use flexbox-like styles. to set flex to 1 to expand the View to fit the screen. And we use justifyContent to 'center' to center horizontally and alignItems to center vertically. Then we put our text in the Text component.

How do you center a component React Native?

To center a component horizontally and vertically in React. js, set its display property to flex and its alignItems and justifyContent properties to center . The components's content will be horizontally and vertically centered. Copied!


2 Answers

Try this... Here's a working demo

  container: {
    flex: 1,
    marginTop: 30,
    marginBottom: 30,
    justifyContent: 'center',
    backgroundColor: '#fff',
  },
  title: {
    fontSize: 28,
    textAlign: 'center',
  },
like image 185
Chris Geirman Avatar answered Sep 29 '22 07:09

Chris Geirman


For anyone looking for a minimal version for the simplest case:

<View style={styles.containerView}>
  <Text style={styles.centeredText}>I'm centered</Text>
</View>

const styles = StyleSheet.create({
  containerView: {
    justifyContent: 'center'
  }
  centeredText: {
    alignSelf: 'center'
  }
})

Align Self

like image 40
David Schumann Avatar answered Sep 29 '22 08:09

David Schumann