【问题标题】:"justifyContent: center" breaks correctly fitting layout with "height: 100%" (React Native / Flexbox)"justifyContent: center" 用 "height: 100%" (React Native / Flexbox) 打破了正确的布局
【发布时间】:2018-03-05 07:11:01
【问题描述】:

这是我的简化代码:

<View style={{flexDirection: "row", width: 200}}>
    <View style={{borderWidth: 2, flex: 1, height: 100}}>
        <Text>flex: 1, height: 80</Text>
    </View>

    <View style={{borderWidth: 2, width: 100, height: "100%", justifyContent: "center"}}>
        <Text>width: 100, height: 100%, justifyContent: center</Text>
    </View>
</View>

这两个盒子应该在高度上对齐。但是当我添加 justifyContent: "center" 以将其中的文本居中居中时,右框的高度完全错误。怎么了?

【问题讨论】:

  • 我认为是因为父 div 有这么高的高度。
  • 上面的代码和下图不一样。。。能不能请大家正确更新一下?
  • 如果父母有height: 100,则不会发生
  • 代码错误,一个是height: 100,一个是height: '100%'。除非您向父元素提供 height: 100,否则它们不可能相同

标签: css react-native flexbox


【解决方案1】:

这是因为 justifyContent 根据给定的空间和高度:'100%' 沿主轴(此处为列)分配所有子级,这里需要分配父级的高度

有两种方法可以使文本居中: 1 - 将 height: '100%' 更改为定义的高度为 100 并将 textAlign : 'center' 更改为文本

<View style={{ flexDirection: 'row', width: 200 }}>
    <View style={{ borderWidth: 2, flex: 1, height: 100, }}>
      <Text>flex: 1, height: 80</Text>
    </View>

    <View
      style={{
        borderWidth: 2,
        width: 100,
        height: 100,

       justifyContent : 'center'
      }}
    >
      <Text style={{textAlign : 'center'}}  >width: 100, height: 100, justifyContent: center</Text>
    </View>
  </View>

2 - 给父级和 textAlign 一个定义的高度:'center' to text

<View style={{ flexDirection: 'row', width: 200, height : 100 }}>
    <View style={{ borderWidth: 2, flex: 1, height: 100, }}>
      <Text>flex: 1, height: 80</Text>
    </View>

    <View
      style={{
        borderWidth: 2,
        width: 100,
        height: '100%',

       justifyContent : 'center'
      }}
    >
      <Text style={{textAlign : 'center'}}  >width: 100, height: 100%, justifyContent: center</Text>
    </View>
  </View>

让我知道这是否适合你)

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 2020-11-17
    • 1970-01-01
    • 2017-04-02
    • 2018-11-22
    • 2016-01-22
    • 2016-11-08
    • 1970-01-01
    • 2017-01-16
    相关资源
    最近更新 更多