文字居中布局

 

通过 alignItems 和 justifyContent 的配合,很容易实现水平垂直方向的居中布局,示例代码如下:

 1 <View
 2     style={{
 3       alignItems: 'center',
 4       justifyContent: 'center',
 5       // 高度确定
 6       height: 60,
 7       borderWidth: 1,
 8     }}>
 9     <Text
10       style={{
11         fontSize: 18,
12         // 文字默认内边距,会导致垂直居中偏下
13         includeFontPadding: false,
14         // 文字默认基于基线对齐,会导致垂直居中偏下
15         textAlignVertical: 'center',
16       }}>
17     我是文字1
18     </Text>
19 </View>

在这段代码中,你只需要给父容器设置{justifyContent: 'center',alignItems: 'center'},使子元素分别在主轴(纵轴)和副轴(横轴)方向居中就可以了。

这里有个小细节,Android 文字默认会有内边距且基于基线对齐,这会导致文字垂直居中时偏下。因此垂直居中时,最好把内边距关掉,并把文字放在中线而不是基线上。

posted @ 2023-06-04 23:58  Ben002  阅读(12)  评论(0编辑  收藏  举报