【问题标题】:How do I align text next to other centered text如何将文本与其他居中文本对齐
【发布时间】:2016-04-23 11:50:35
【问题描述】:

我有两段文字。我需要第一块水平和垂直居中,第二块就在它旁边。目前代码如下所示:

<View style={styles.runningTimeWrapper}>
  <Text style={styles.loggedTime}>00:00</Text>
  <Text style={[styles.loggedTime, styles.loggedSeconds]}>00</Text>
</View>

如何设置样式以使 00:00 居中?使用固定宽度不是一个选项,因为我需要它在任何屏幕尺寸上工作。

这是它目前的样子:

样式:

  loggedTime: {
    color: Variables.PURPLE,
    fontSize: 44,
    alignSelf: 'center',
  },
  loggedSeconds: {
    fontSize: 22,
    alignSelf: 'flex-end',
    paddingBottom: 8
  },

  runningTimeWrapper: {
    flexDirection: 'row',
    justifyContent: 'center',
    flex: 1,
  },

想要的效果是让 hh:mm 的列与屏幕中心对齐,秒紧挨着分钟。

在所有“中心”引用中,我说的是水平中心(x 轴),而不是垂直(y 轴)(使用 alignItems /self 设置)

【问题讨论】:

    标签: css react-native flexbox


    【解决方案1】:

    您可以将第二个跨度设置为position:absolute,这样会超出正常的内容流,并确保小时/分钟在容器中居中。

    .wrapper {
      display: flex;
      justify-content: center;
      position: relative;
      font-family: sans-serif;
    }
    .hm {
      font-size: 44px;
    }
    .s {
      font-size: 22px;
      position: absolute;
      bottom: 5px;
    }
    <div class="wrapper">
      <span class="hm">12:34</span>
      <span class="s">56</span>
    </div>

    事实上,你并不真的需要 flexbox,text-align:center 可能就足够了。

    .wrapper {
      text-align: center;
      position: relative;
      font-family: sans-serif;
    }
    .hm {
      font-size: 44px;
    }
    .s {
      font-size: 22px;
      position: absolute;
      bottom: 5px;
    }
    <div class="wrapper">
      <span class="hm">12:34</span>
      <span class="s">56</span>
    </div>

    【讨论】:

      【解决方案2】:

      您需要 3 个内部包装器视图:左侧一个空的,然后将大小数字分别包装在各自的包装器中。然后给左右包装器 flex: 1 使它们的宽度相同。

      https://rnplay.org/apps/hLBFng

      【讨论】:

        【解决方案3】:

        我不能 100% 确定我理解您的目的。您是否试图让loggedTime 完全居中,而loggedSeconds 则向右偏移?或者你只是想让两者都成为中心/中心?

        我想我可以通过设置flexDirection: 'row' 并在秒数上添加一些paddingTop 来得到一些东西。

        这是demo on rnplay.org

        var styles = StyleSheet.create({
         loggedTime: {
            color: '#FF5500',
            fontSize: 44,
            alignSelf: 'center',
          },
          loggedSeconds: {
            fontSize: 22,
            paddingTop: 20,
            paddingBottom: 8
          },
        
          runningTimeWrapper: {
            flexDirection: 'row',
            justifyContent: 'center',
            flex: 1,
          },
        });
        

        【讨论】:

        • 通过在 runningTimeWrapper 上设置 justifyContent 中心,那么时间和秒的总和将居中。我尝试做的是居中的时间,以及它旁边的秒数。我在问题的末尾添加了一些说明
        • 我认为 alexp 和 Pangloss 的其他两个答案看起来可以解决。
        猜你喜欢
        • 1970-01-01
        • 2016-01-15
        • 2021-05-28
        • 2018-05-12
        • 1970-01-01
        • 2016-01-22
        • 1970-01-01
        • 2022-11-01
        • 2015-07-29
        相关资源
        最近更新 更多