React Native absolute positioning horizontal centre

后端 未结 7 765
栀梦
栀梦 2021-01-30 06:23

It seems that with position:absolute in use an element cannot be centred using justifyContent or alignItems. There\'s a workaround to use

相关标签:
7条回答
  • 2021-01-30 06:30

    If you want to center one element itself you could use alignSelf:

    logoImg: {
        position: 'absolute',
        alignSelf: 'center',
        bottom: '-5%'
    }
    

    This is an example (Note the logo parent is a view with position: relative)

    0 讨论(0)
  • 2021-01-30 06:31

    It's very simple really. Use percentage for width and left properties. For example:

    logo : {
      position: 'absolute',
      top : 50,
      left: '30%',
      zIndex: 1,
      width: '40%',
      height: 150,
    }
    

    Whatever width is, left equals (100% - width)/2

    0 讨论(0)
  • 2021-01-30 06:39

    create a full-width View with alignItems: "center" then insert desired children inside.

    import React from "react";
    import {View} from "react-native";
    
    export default class AbsoluteComponent extends React.Component {
      render(){
        return(
         <View style={{position: "absolute", left: 0, right: 0, alignItems: "center"}}>
          {this.props.children}
         </View>    
        )
      }
    }
    

    you can add properties like bottom: 30 for bottom aligned component.

    0 讨论(0)
  • 2021-01-30 06:48

    You can center absolute items by providing the left property with the width of the device divided by two and subtracting out half of the element you'd like to center's width.

    For example, your style might look something like this.

    bottom: {
        position: 'absolute',
        left: (Dimensions.get('window').width / 2) - 25,
        top: height*0.93,
    }
    
    0 讨论(0)
  • 2021-01-30 06:49

    Wrap the child you want centered in a View and make the View absolute.

    <View style={{position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'center', alignItems: 'center'}}>
      <Text>Centered text</Text>
    </View>
    
    0 讨论(0)
  • 2021-01-30 06:52
    <View style={{...StyleSheet.absoluteFillObject, justifyContent: 'center', alignItems: 'center'}}>
      <Text>CENTERD TEXT</Text>
    </View>
    

    And add this

    import {StyleSheet} from 'react-native';
    
    0 讨论(0)
提交回复
热议问题