JackKalish
JackKalish

Reputation: 1585

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

Upvotes: 6

Views: 17921

Answers (6)

sepnil
sepnil

Reputation: 19

set in main View style flex:1 and in Text set textAlign:'center'

Upvotes: 1

Bisma Azher
Bisma Azher

Reputation: 749

use textAlign: 'center' property to center text

use alignSelf:'center' property to center View

<View style={{alignSelf:'center'}}>

      <Text style={{textAlign:'center'}}>I'm centered</Text>

</View>

Upvotes: 2

Dev Kingdom
Dev Kingdom

Reputation: 21

Add justifyContent: 'center' to the container view. React native works different to react. So alignItems not working, instead justifyContent works.

Upvotes: 1

David Schumann
David Schumann

Reputation: 14793

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

Upvotes: 2

Samar Khan
Samar Khan

Reputation: 1

Adding flexDirection:'column' helps the items to be aligned centrally column by column:

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

Upvotes: 0

Chris Geirman
Chris Geirman

Reputation: 9684

Try this... Here's a working demo

  container: {
    flex: 1,
    marginTop: 30,
    marginBottom: 30,
    justifyContent: 'center',
    backgroundColor: '#fff',
  },
  title: {
    fontSize: 28,
    textAlign: 'center',
  },

Upvotes: 8

Related Questions