I want my text
and button
at the top of the screen, but both the elements have a few gaps between, so I added marginBottom
to my text
and then that text
went to the top. But I want that button
to be at the top so I added marginBottom
to the button
too, but now it’s not going to the top.
How can I position it to the top? Where is the style issue coming from? Please, explain my mistake as well.
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text style={{ margin: 16, marginBottom: '80%', backgroundColor: 'black' }}>Hello World</Text>
<View style={{ marginBottom: '80%' }}>
<Button title='Click me' />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
2
Answers
You’re using
alignItems: 'center'
andjustifyContent: 'center'
.These two properties combined make the contents of
container
be positioned in the center.alignItems:center
vertically centers the contents, andjustifyContent:center
horizontally centers the contents.Since
Text
is the upper child element, giving it amarginBottom
will space it out from theView
element containing theButton
. If you compare your screen with and without thatmarginBottom
on theText
you’ll notice that the button also moves slightly to the bottom if you include themarginBottom
on theText
.So in short, your code is doing exactly what you tell it to do:
container
tries to position all children to its center.To fix this, you might want to remove the
container:{ alignItems:'center', }
property. This will most likely push all your elements to the top of the container. After that you might simply usemarginTop
on yourText
element to push the contents down.Change both marginBottom %80 to "auto".