Search code examples
reactjsreact-nativeflexboxcss-positionreact-native-flexbox

Flexbox positioning text inside image


I'm using React Native and trying to create a specific layout.

I have an image, vertically & horizontally centred (within a View) and some Text on top of the image also vertically & horizontally centred. The Text needs to come on top of image/background image therefore I put it inside the image tag.

Now the content of that text can be very long and because it is inside the image tag, it wraps.

How can I make it so the content inside Text won't wrap and still be on top of the Image?

My layout so far:

enter image description here

The layout I'm trying to achieve

enter image description here

My code:

<TouchableHighlight onPress={onPress}>
  <View style={styles.categoryContainer}>
    <View style={styles.leftContainer}>
      <View style={styles.categoryIndexContainer}>
        <Text style={styles.categoryIndex}>01</Text>
      </View>
    </View>
    <View style={styles.middleContainer}>
      <Image source={img} style={styles.categoryImage}>
        <Text style={styles.categoryName}>Some very long title name</Text>
      </Image>
    </View>
    <View style={styles.rightContainer}></View>
  </View>
</TouchableHighlight>

const styles = StyleSheet.create({
  categoryContainer: {
    flexDirection: 'row',
  },
  leftContainer: {
    width: 50,
    paddingLeft: 15,
    paddingTop: 30,
  },
  middleContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1,
    flexDirection: 'row',
  },
  rightContainer: {
    width: 50,
  },
  categoryName: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: 40,
    textAlign: 'center',
    backgroundColor: 'transparent',
    flexWrap: 'nowrap',
  },
  categoryImage: {
    alignItems:'center',
    justifyContent:'center',
    flexWrap: 'nowrap',
  },
})

Thanks


Solution

  • You should specify on categoryName style: position: 'absolute' then set the top, left, right, bottom attributes until you place the Text above the Image.