Home > Software engineering >  How do you vertically and horizontally center a View with respect to another View that is at a highe
How do you vertically and horizontally center a View with respect to another View that is at a highe

Time:04-07

Image of what I am envisioning

I'm trying to add a center tick mark to a slider.

Is it possible to vertically and horizontally center View 1 with respect to View 2 and at the same time render View 2 above View 1 (using zIndex)? I can accomplish this by placing View 1 below View 2 in the Y direction and set the margin of View 1 so it appears underneath View 2 (in the Z direction). Is that the correct way to do this?

Accomplishing this by fiddling with the margins seems like it could cause problems on different size screens.

CodePudding user response:

You can surround the Views with a parent View like so:

<View style={{ width: '100%', justifyContent: 'center', alignItem: 'center' }}>
  //horizontal
  <View style={{ zIndex: 1, elevation: 1, width: '100%', height: '20'% }}></View>
  //vertical
  <View style={{ zIndex: 0, elevation: 0, height: '100%', width: '20%' }}></View>
</View>

This will adjust dynamically depending on screen size since all height and width values are set using percentages.

CodePudding user response:

Try giving view1 and view2 absolute positions, and place them in a parent container that centers vertically and horizontally. This will allow them to overlap without having to play with margin, and will naturally place the view2 on top of view1 without having to use zIndex

export default function App() {
  return (
    <View style={styles.container}>
      <View style={styles.specialContainer}>
        <View style={styles.tall}/>
        <View style={styles.long}/>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  specialContainer:{
     width:300,
     aspectRatio:1,
     backgroundColor:'pink',
     alignItems:'center',
     justifyContent:'center'
  },
  long:{
    position:'absolute',
    backgroundColor:'purple',
    width:'60%',
    height:24,
    // alignSelf:'center'
  },
  tall:{
    position:'absolute',
     backgroundColor:'green',
    height:'60%',
    width:24,
    // alignSelf:'center',
  }
});

Try it out here

  • Related