安卓文本无法垂直居中

Web前端评论275阅读模式

安卓 webview 的字体大小在小于 12 像素的时候无法使用行高来垂直居中。目前在微信等应用都存在该问题,而在最新的移动端 Chrome 浏览器上无该问题(截止本文编写时间,微信客户端的 chrome 版本为 57,chrome 版本为 70)。

安卓文本无法垂直居中-图片1

尝试方案:

table 布局:文本偏上

<div class="solution" style="display: table; height: 16px;">
  <span style=" display: table-cell; font-size: 10px; vertical-align: middle;">hot 热门</span>
</div>

flex 布局:文本偏上

<div class="solution" style="display: inline-flex; align-items: center; height: 16px; line-height: 1; font-size: 10px;">
  <span>hot 热门</span>
</div>

transform 缩放:文本居中了,但是 transform 不能还原元素在 dom 上的占用区域大小

<div class="solution" style="height: 32px; line-height: 32px; font-size: 20px; transform: scale(0.5, 0.5); transform-origin: left top;">
  <span>hot 热门</span>
</div>

zoom 缩放:文本偏上

<div class="solution" style="height: 32px; line-height: 32px; font-size: 20px; zoom: 0.5;">
  <span>hot 热门</span>
</div>

固定高度+内边距+行高设定为字体大小:文本偏上

<div class="solution" style="box-sizing: border-box; height: 16px; padding: 3px 0; line-height: 10px; font-size: 10px;">
  <span>hot 热门</span>
</div>

固定高度+内边距+行高设为 normal:文本偏上

<div class="solution" style="box-sizing: border-box; height: 16px; padding: 3px; line-height: normal; font-size: 10px;">
  <span>hot 热门</span>
</div>

内边距+行高设为 normal:文本居中,但在部分客户端上不居中

<div class="solution" style="box-sizing: border-box; padding: 2px; line-height: normal; font-size: 10px;">
  <span>hot 热门</span>
</div>

行高+字体大小设为 initial:文本居中,在最新的 Chrome 浏览器上不居中

<div class="solution" style="line-height: 16px; font-size: initial;">
  <span style="font-size: 10px;">hot 热门</span>
</div>

效果图:

安卓文本无法垂直居中-图片2

完美的解决办法没有,可以尝试:

在不同的安卓客户端上测试上述方法发现以下三个方法或许可以帮助解决居中问题,我们可以根据实际客户端的支持情况来选择其中一种方式来解决无法居中问题。

transform 缩放

<div class="solution" style="height: 32px; line-height: 32px; font-size: 20px; transform: scale(0.5, 0.5); transform-origin: left top;">
  <span>hot 热门</span>
</div>

内边距+行高设为 normal

<div class="solution" style="box-sizing: border-box; padding: 2px; line-height: normal; font-size: 10px;">
  <span>hot 热门</span>
</div>

行高+字体大小设为 initial

<div class="solution" style="line-height: 16px; font-size: initial;">
  <span style="font-size: 10px;">hot 热门</span>
</div>

文章来自网络

经测试在安卓上貌似只有火狐是垂直居中Chrome和其它所谓国产浏览器,包括微信在内都不能垂直居中,都是向上偏移1PX,特别是在一些边距较小的按钮上尤为明显。

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

拖动滑块以完成验证