Reputation: 409
I am new to flexbox styling. I am facing problem while trying to align an element in the flexbox to the rightmost corner. I have written the following code to align the plus symbol in the image to the right corner of the red box but its not working as expected. Kindly help me to resolve this issue.
<View style={main_container}>
<ScrollView>
<TouchableHighlight>
<View style={container}>
<Image style={imageStyle} source={{uri: this.props.data.picture}} />
<Text style={textStyle}> {this.props.data.company} </Text>
<Text style={iconStyle}>
<Icon name={'plus-circle'} size={20} color={'#003057'} />
</Text>
</View>
</TouchableHighlight>
</ScrollView>
<Footer />
</View>
const styles = StyleSheet.create({
main_container: {
flex: 1,
flexDirection: 'column',
marginTop: 70
},
container: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
margin: 6,
backgroundColor: 'red'
},
imageStyle: {
width: 50,
height: 50
},
textStyle: {
fontSize: 10
},
iconStyle: {
backgroundColor: 'yellow',
alignSelf: 'flex-end' //why is it aligning the image vertically ?
}
});
Upvotes: 9
Views: 34352
Reputation: 22974
This will do it in react-native to have everything line up on the y-axis properly. The key is the flex:1
on the center element.
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Image source={{uri: this.props.data.picture}} />
<Text style={{flex:1}}>{this.props.data.company}</Text>
<Icon name={'plus-circle'} size={20} color={'#003057'} />
</View>
Upvotes: 12
Reputation: 87303
flex-end
work cross axis and push the icon vertically to the end (bottom of its parent), which you can see in your code, that it is not centered as the text and image.
To make this work you need display: flex
on container:
, set flex: 1;
on textStyle:
which will make it take all available space and push the iconStyle:
to the far right.
If margin-left: auto
would be available (on the iconStyle:
), that would do it without the flex: 1
, though you still need the display: flex
on the container:
and there should be display: flex
on the main_container:
too, unless that is automatically added elsewhere (same goes for container:
)
Sample snippet
div {
display: flex;
align-items: center;
background: lightgray;
height: 50px;
margin-bottom: 5px
}
span {
padding: 5px;
}
div.nr1 span:nth-child(2) {
flex: 1;
}
div.nr2 span:nth-child(3) {
margin-left: auto;
}
<div class="nr1">
<span>image</span>
<span>text</span>
<span>icon</span>
</div>
<div class="nr2">
<span>image</span>
<span>text</span>
<span>icon</span>
</div>
Upvotes: 10