Skip to content
Advertisement

React Native: Align Horizontally – Center and Right

In my React Native project, I need to align two elements. One should be in the centre and the other should be extreme right of the screen. However, I’m unable to get it right.

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.mainTitle}>
        <Text style={{display: 'flex'}}>
          Main Title
        </Text>
        <Text
        style={{
          color: '#528bb4',
          fontSize: 14,
          fontWeight:600,
          marginLeft: 'auto',
          width:10,
          display:'flex',
          marginRight:10
        }}
      >?</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  mainTitle: {    display: 'flex', flexDirection: 'row', backgroundColor: '#fff',height: '30%', width: '100%',alignItems: 'center',justifyContent: 'center',},
});

Snack URL: https://snack.expo.io/iXjlvlGpd

I’m unable to get the main element in center and the next element to the right.

Advertisement

Answer

You can do something like below, have am absolute position for the right Text and have alignself center for the text

  <View style={styles.mainTitle}>
    <Text style={{ display: 'flex', alignSelf: 'center' }}>Main Title</Text>
    <Text
      style={{
        color: '#528bb4',
        position: 'absolute',
        fontSize: 14,
        fontWeight: 600,
        right: 10,
        width: 10,
        display: 'flex',
        marginRight: 10,
      }}>
      ?
    </Text>
  </View>

https://snack.expo.io/@guruparan/dfddf9

Advertisement