Home > Enterprise >  How to put an Image to top of screen that is horizontally centered in React-Native?
How to put an Image to top of screen that is horizontally centered in React-Native?

Time:03-07

I'm trying to put an image to be at the top of the screen (top: 0) but I cannot achieve that for some reason. Below is my shortened code:

export default function App() {
  return (
    <View style={styles.container}>
      <StatusBar style="light" />

      <ImageBackground source={backgroundImage} style={styles.bgimage}>
        <View style={styles.banner}>
          <Image
            source={banner}
            style={{ width: 200, resizeMode: "contain" }}
          />
        </View>

        <View style={styles.loginForm}>
          <Text style={styles.heading}>WELCOME</Text>

          <View style={styles.section}>
            <Image source={user} style={styles.inputImage} />
            <TextInput
              style={styles.textInput}
              placeholder="Korisničko ime"
              underlineColorAndroid={"transparent"}
              placeholderTextColor="white"
            />
          </View>
          <View style={styles.section}>
            <Image source={password} style={styles.inputImage} />
            <TextInput
              style={styles.textInput}
              placeholder="Lozinka"
              underlineColorAndroid={"transparent"}
              placeholderTextColor="white"
            />
          </View>

          <TouchableOpacity style={styles.loginButton}>
            <Text style={{ color: "red" }}>LOGIN</Text>
          </TouchableOpacity>
        </View>
      </ImageBackground>
    </View>
  );
}

And here are the styles that affect these objects:

container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  bgimage: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    width: "100%",
    resizeMode: "contain",
  },
  loginForm: {
    width: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  banner: {
    position: "absolute",
    top: 0,
  }

What happens to me is that my image goes at the very bottom, below my login form but I want it above, just below the status bar.

CodePudding user response:

A possible solution is to set your container to the full width of your viewport, set your flex-direction of the container to column, and then use the following on the container:

align-items: center
justify-content: flex-start

CodePudding user response:

{
 height: 100,   // height and width as per you content
 width: '90%',
 alignSelf: 'center',
 position: 'absolute', // If you want the position to be fixed at top
 top: 0,
}
  • Related