Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-native: margin not taken into account in a flex layout

I encountered a few times issues with margins when layouting views using flexbox.

I managed to reproduce the issue with a small code snippet:

Here is a custom component:

class MyView extends Component {
  render() {
    return (
      <View style={
        {
          backgroundColor: 'green',
          width: 50,
          height: 50
        }
      }/>
    );
  }
}

and here is how I use it:

<View style={{ flexDirection: 'column' }}>
  <MyView />
  <MyView style={{ marginTop: 12 }}/>
</View>

So I am expecting to see 2 green squares on top of each other, separated by 12px (due to the marginTop). Instead here is what I see:

nomargin

The two squares touch each other. I have no idea why the margin is not taken into account.

I tried debugging the bottom view with the inspector tool, here is what's getting displayed:

nomargin-debug

You can actually see the margin on this image (light orange). Any idea why the margin is not taken into account?

like image 367
MartinMoizard Avatar asked Jun 05 '26 03:06

MartinMoizard


1 Answers

I faced the same issue when using flex and I used

justifyContent = "space-between"

margin top and marginBottom didn't work for me .Later when I removed the justifyContent and just put

alignItems: "center", flexDirection: "column"

instead margin top and bottom worked for me .

like image 142
Payel Dutta Avatar answered Jun 07 '26 22:06

Payel Dutta



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!