15

I have the following

<View style={{maxWidth: 700}}>
  <View style={{backgroundColor: 'red', flexDirection: 'row', justifyContent: 'space-between'}}>
    <Text>Left Item</Text>
    <Text>Right Item</Text>
  </View>
</View>

which is working as I'd expect on a large device (vertical black lines are edges of emulator screen).

enter image description here

All I would like to do is center this on the screen.

When I attempt to do so by adding alignSelf: 'center' to the parent

<View style={{maxWidth: 700, alignSelf: 'center'}}>
  <View style={{backgroundColor: 'red', flexDirection: 'row', justifyContent: 'space-between'}}>
    <Text>Left Item</Text>
    <Text>Right Item</Text>
  </View>
</View>

the width is lost.

enter image description here

I assume this is because by default alignSelf it is 'stretch'. Is there a way to both stretch the content to use maxWidth and center it on the screen?

0

2 Answers 2

19

Try using flex:1 along with maxWidth to both make it stretch but limit the width to 700

<View style={{flexDirection:'row', alignItems: 'center', justifyContent: 'center'}}>
    <View style={{flex:1, maxWidth: 700, backgroundColor:'red', flexDirection:'row', justifyContent:'space-between'}}>
        <Text>Left Item</Text>
        <Text>Right Item</Text>
    </View>
</View>
2
  • Not terribly important but alignItem: 'center' is not necessary here since since I only care about centering horizontally. It's interesting to me that setting {{flexDirection: 'row', justifyContent: 'center'}} on the parent view works but setting only {{alignItems: 'center'}} doesn't work. I would have assumed both would do the same thing in terms of horizontal alignment.
    – Steven
    Commented Sep 16, 2016 at 19:14
  • Thanks for flex: 1
    – onmyway133
    Commented Nov 5, 2018 at 13:33
9

Using maxWidth along with width: '100%' does the trick for me.

3
  • That is not an either or - are you saying your use both together? Commented Feb 4, 2020 at 20:36
  • Yes. flex: 1 didn't work in my case, so I used width: '100%' together with a maxWidth of the desired value. This stretches the container to 100% of the window width until maxWidth is reached. Commented Feb 5, 2020 at 8:30
  • This is also the solution that worked for me. Commented Aug 16, 2021 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.