skip to Main Content

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


  1. You’re using alignItems: 'center' and justifyContent: 'center'.
    These two properties combined make the contents of container be positioned in the center. alignItems:center vertically centers the contents, and justifyContent:center horizontally centers the contents.

    Since Text is the upper child element, giving it a marginBottom will space it out from the View element containing the Button. If you compare your screen with and without that marginBottom on the Text you’ll notice that the button also moves slightly to the bottom if you include the marginBottom on the Text.

    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 use marginTop on your Text element to push the contents down.

    Login or Signup to reply.
  2. Change both marginBottom %80 to "auto".

      return (
        <View style={styles.container}>
          <Text
            style={{ margin: 16, marginBottom: "auto", backgroundColor: "white" }}
          >
            Hello World
          </Text>
          <View style={{ marginBottom: "auto" }}>
            <Button title="Click me" />
          </View>
        </View>
      );
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search