Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native FlexBox: Why does adding `alignItems` prevent child from having 100% width?

In my React Native app, I have a parent View that container a child View that contains a Text element. By default, the child View's width stretches to fill the parent. But if I add alignItems: 'center', the child moves to the center but also its width shrinks to be only as wide as to fit the text it contains.

Here is a snack. Un-comment alignItems: 'center' to see the difference: https://snack.expo.io/@gkeenley/alignitems-example

Does anyone know why this happens?

like image 728
gkeenley Avatar asked Oct 28 '25 08:10

gkeenley


1 Answers

The child doesn't have an explicit width, so it's width would normally be just enough to surround the text that it contains, and that's what you're seeing when alignItems is set to 'center'. The reason you saw it taking up the full width before is that the default value for alignItems is 'stretch', which causes child's normal width to not matter and it instead gets stretched to take up all the space.

If you'd like the child to be larger in your centered version, you can either give it an explicit width:

child: {
  height: '100%',
  width: '50%',
  backgroundColor: 'red'
}

...or use padding to put some extra separation around the text.

child: {
  height: '100%',
  padding: 5,
  backgroundColor: 'red'
}
like image 155
Nicholas Tower Avatar answered Oct 31 '25 00:10

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!