React Native绝对定位水平中心

时间:2016-05-19 08:15:48

标签: position react-native flexbox absolute

似乎在使用position:absolute时,无法使用justifyContentalignItems来居中使用元素。有一种使用marginLeft的解决方法,但即使使用尺寸来检测设备的高度和宽度,也不会对所有设备显示相同的内容。

  bottom: {
    position: 'absolute',
    justifyContent: 'center',
    alignItems: 'center',
    top: height*0.93,
    marginLeft: width*0.18,
  },
  bottomNav: {
    flexDirection: 'row',
  },

8 个答案:

答案 0 :(得分:136)

将您想要居中的孩子包裹在视图中并使视图绝对。

<View style={{position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'center', alignItems: 'center'}}>
  <Text>Centered text</Text>
</View>

答案 1 :(得分:31)

如果您想将一个元素本身居中,则可以使用 alignSelf

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

这是一个示例(请注意徽标父级是具有位置:相对的视图)

enter image description here

答案 2 :(得分:10)

您可以通过提供左侧属性将设备的宽度除以2并减去您想要居中宽度的元素的一半来居中绝对项目。

例如,您的样式可能看起来像这样。

bottom: {
    position: 'absolute',
    left: (Dimensions.get('window').width / 2) - 25,
    top: height*0.93,
}

答案 3 :(得分:2)

使用View创建全角alignItems: "center",然后在其中插入所需的子级。

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>    
    )
  }
}

您可以为底部对齐的组件添加诸如bottom: 30之类的属性。

答案 4 :(得分:0)

真的很简单。为widthleft属性使用百分比。例如:

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

无论width是什么,left等于(100% - width)/2

答案 5 :(得分:0)

<View style={{...StyleSheet.absoluteFillObject, justifyContent: 'center', alignItems: 'center'}}>
  <Text>CENTERD TEXT</Text>
</View>

并添加

import {StyleSheet} from 'react-native';

答案 6 :(得分:0)

好吧,我会用这种方式来居中绝对视图

  <View style={{ position: 'absolute', left: '50%', marginLeft: -22 }}>
           <View style={{ position: 'absolute', width: 44, height: 44}}>
             <Ionicons name="close" color="#4775f2" size={32} />
           </View>
   </View>

请注意,在包装我使用的 Icon 容器的 View 中,我使用的是 left: 50% 并且 marginLeft 是特殊的,因为您需要准确地放置孩子的中间宽度并将其转为负数,在这种情况下为 44你可以在上面看到,就是这样

答案 7 :(得分:-1)

您可以尝试代码

<View
    style={{
      alignItems: 'center',
      justifyContent: 'center'
    }}
  >
    <View
      style={{
        position: 'absolute',
        margin: 'auto',
        width: 50,
        height: 50
      }}
    />
  </View>
相关问题