【问题标题】:How to center text on the screen when it's width is not 100% [duplicate]当宽度不是100%时如何在屏幕上居中文本[重复]
【发布时间】:2021-02-11 01:30:51
【问题描述】:

我想将第二段文本居中。第一部分有一个占据部分宽度的图标。第二个文本没有占据屏幕的整个宽度,所以当我将 textAlign 应用到中心时,文本中心应该考虑它的宽度。

第一个下方的另一个文本占据了整个宽度,因此它实际上在屏幕的中心对齐,而不是相对于它上面的第一段文本居中。

代码:

<View style={{ marginBottom: 25 }}>
   <View style={{ flex: 1, flexDirection: "row", alignItems: "center", marginTop: 15 }}>
      <MaterialIcons onPress={() => console.log("funciona por favor!!")} name="close" size={20} style={{ color: "#FFF" }} />
      <Text style={{ flex: 1, color: "#FFF", fontSize: 24, textAlign: "center" }}>Configurações</Text>
   </View>
   <Text style={{ color: COLORS.white1, fontSize: 24, marginTop: 0, alignSelf: "center" }}>Configurações</Text>
</View>

我尝试了什么: 图标有 30px 的宽度,所以我尝试了文本的负值边距并将其居中,但它覆盖了图标,并且需要按下此图标,因此按下不起作用。

感谢您的帮助,我希望我已经清楚地暴露了问题。

【问题讨论】:

  • 在按钮右侧放置同样宽的不可见内容。我强烈建议使用网格布局
  • @Psi 不错的技巧,它奏效了,谢谢。我不习惯使用网格布局,如果可能的话回答这个问题,展示如何用网格来做。谢谢!
  • 只要搜索 css grid,你会发现一些非常好的文档,例如 css-tricks.com(与我无关)

标签: css reactjs react-native


【解决方案1】:

您可以在内容的右侧添加一个边距,以抵消它从右侧推送的文本量。

<View style={{ marginBottom: 25, backgroundColor: 'grey' }}>
  <View style={{ flex: 1, flexDirection: "row", marginTop: 15 }}>
      <MaterialIcons name="close" size={20} style={{ color: "#FFF" }} />
      <Text style={{ flex: 1, color: "#FFF", fontSize: 24, textAlign: "center", marginRight: 20 }}>Configurações</Text>
  </View>
  <Text style={{ color: '#fff', fontSize: 24, marginTop: 0, alignSelf: "center" }}>Configurações</Text>
</View>

【讨论】:

    【解决方案2】:

    让你的按钮成为一个网格:

    div.button {
      background:blue;
      padding:4px;
      color:white;
      font-family:"Verdana";
      width:50vw;
      display:grid;
      grid-template-columns: 5% auto 5%;
    }
    
    div.button div.caption {
      text-align:center;
    }
    <div class="button">
      <div class="left">ICON</div>
      <div class="caption">Your caption here</div>
      <div class="right"></div>
    </div>

    使用这种方法,您定义了三列,将您的图标放在最左边的那一列,将标题放在中间的那一列,并留下一列与左边一样宽,使中间列实际上居中。

    【讨论】:

      【解决方案3】:

      您将关闭图标包裹在 absolute 视图中并相应地设置左侧位置。这样你的文字就会和下面的文字对齐了

      <View style={{position:'absolute',left:0}}>      
          <MaterialIcons onPress={() => console.log("funciona por favor!!")} name="close" 
                         size={20} style={{ color: "#FFF" }} />
      </View>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-30
        • 2015-09-10
        • 2012-01-13
        • 2019-10-23
        • 2011-12-21
        • 2012-04-02
        • 2017-01-03
        • 2013-07-27
        相关资源
        最近更新 更多