Reputation: 20222
In React Native, I have a Text
element contained within a View
:
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
Buy this!
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
width: 200,
height: 200,
backgroundColor: '#77EB11'
},
paragraph: {
backgroundColor: '#F55008',
textAlign: 'center',
width: '100%',
height: '100%'
},
});
I want the text to be centered both horizontally and vertically. Normally, this would be achieved by using justify-content
and align-items
in the containing View
. However, I am working on Windows and because of this issue, I also have the constraint that the Text
must occupy the whole View
, otherwise I will not be able to click the whole View
when I will put a callback in it, later.
I also created a React fiddle with the exact same problem, but which may be easier to use.
Currently, the text is centered only vertically. How can I center it horizontally as well?
Again, the most important constraint is that the <Text>
tag should occupy all of the containing <View>
.
Upvotes: 1
Views: 3180
Reputation: 6280
You can use
display: table;
on the containerdisplay: table-cell; vertical-align: middle;
on the paragraph.const styles = {
container: {
width: 200,
height: 200,
backgroundColor: '#77EB11',
display: 'table'
},
paragraph: {
backgroundColor: '#F55008',
textAlign: 'center',
width: '100%',
height: '100%',
display: 'table-cell',
verticalAlign: 'middle'
},
};
If you want to look at other strategies on how to align text vertically, try taking a look at this article ALIGN TEXT VERTICALLY
Upvotes: 1