Reputation: 4483
I am trying to set the margins on a box in react native, but the behavior is very strange. If I set marginLeft: 10, the margin is 10 on the left. But if I also set marginRight: 10, then the margin on the left is 20 and on the right is 20. Here is my code:
// ResultList.js
const box = {
backgroundColor: 'green',
marginLeft: 10,
marginRight: 10
}
return (
<View style={box}>
<ResultItem />
<ResultItem />
<ResultItem />
<ResultItem />
<ResultItem />
</View>
)
// ResultItem.js
return (
<View style={{margin: 0}}>
<Text style={{margin: 0}}>
This is text Here. This is more text testing.
This is text Here. This is more text testing
</Text>
</View>
)
This code produces the following image. Where I have drawn the black bars is where the green box should align to. It is worth noting that if I remove marginRight: 10
, then the left margin behaves correctly. Only when I add in the marginRight is it wrong.
Code for Blue background view:
App.js
return (
<View style={styles.container}>
<ResultList />
</View>
);
container: {
flex: 1,
alignItems: 'center',
backgroundColor: 'blue'
}
Upvotes: 5
Views: 28043
Reputation: 21
Can you remove all margin and add paddingHorizontal to your container class like this
container: {
flex: 1,
alignItems: 'center',
backgroundColor: 'blue',
paddingHorizontal: 10
}
Upvotes: 2
Reputation: 921
as i see you defined margin once in const box = { ... }
so result item will be rendered in a view that have marginRight: 10 , marginLeft : 10
style,and if you set the margin in ResultItem.js component ,total margin is: box margin + ResultItem.js margin.
and if you dont set the width
in <Text>
component,width must be in range of 0 and text lenght,i suggest you to set the width
in <Text>
component so that will be easier to set margin and see the result
Upvotes: 0
Reputation: 2065
Try to use marginHorizontal instead of marginLeft and marginRight.
const box = {
backgroundColor: 'green',
marginHorizontal:10
}
Upvotes: 5