首页 > 解决方案 > 当宽度不是 100% 时如何在屏幕上居中显示文本

问题描述

我想将第二段文字居中。第一部分有一个图标,占据了部分宽度。第二个文本不占用屏幕的整个宽度,因此当我将 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,所以我尝试为文本设置负值边距并将其居中,但它覆盖了图标,并且需要按下此图标,因此按下不起作用。

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

标签: cssreactjsreact-native

解决方案


使您的按钮成为网格:

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>

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


推荐阅读