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 ?
}
});
The align-content property accepts 6 different values: flex-start : lines packed to the start of the container. flex-end : lines packed to the end of the container.
In addition to the initial value of stretch, you can give align-items a value of flex-start , in which case they align to the start of the container and no longer stretch to the height. The value flex-end moves them to the end of the container on the cross axis. We can also do baseline alignment.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With