console
<div>在 Android 手机上line-height 垂直居中出现偏离</div>
<p>导致这个问题的本质原因可能是Android在排版计算的时候参考了primyfont字体的相关属性(即HHead Ascent、HHead Descent等),而primyfont的查找是看`font-family`里哪个字体在fonts.xml里第一个匹配上,而原生Android下中文字体是没有family name的,导致匹配上的始终不是中文字体,所以解决这个问题就要在`font-family`里显式申明中文,或者通过什么方法保证所有字符都fallback到中文字体。根据这2个思路,目前我找到了2个解决方案:</p>
<p>1.针对Android 7.0+设备:</p>
<p>
<html>上设置 lang 属性:<html lang="zh-cmn-Hans">,同时font-family不指定英文,如 font-family: sans-serif 。这个方法是利用了浏览器的字体fallback机制,让英文也使用中文字体来展示,blink早期的内核在fallback机制上存在问题,Android 7.0+才能ok,早期的内核下会导致英文fallback到Noto Sans Myanmar,这个字体非常丑。</p>
<p>2. 针对MIUI 8.0+设备:</p>
<p>设置 font-family: miui 。这个方案就是显式申明中文的方案,MIUI在8.0+上内置了小米兰亭,同时在fonts.xml里给这个字体指定了family name:miui,所以我们可以直接设置。</p>
<p>作者:周祺
链接:https://www.zhihu.com/question/39516424/answer/274374076</p>
<div>在 Android 设备上文字明显偏上的情况一般有两种:</div>
<ul>
<li>
情况1: 字体小于12px
<div class="question1">
123
</div>
</li>
<li>
情况2: 文字, 行高, 容器高度为奇数
<div class="question2">
123
</div>
</li>
</ul>
<div>
中文font-family, 没有偏移
<div class="normal">
font-family: sans-serif;
</div>
</div>
---------------
<div>尝试解决方法如下:</div>
<h3>字体10px 居中方法对比</h3>
<p>
结论: 放大缩小法和添加border有效.
</p>
<h4>表格居中</h4>
<div class="question1 box1">
<div class="child1">123</div>
</div>
<h4>flex 居中</h4>
<div class="question1 box2">
123
</div>
<h4>数据翻倍, 然后用 scale 缩小</h4>
<div class="question1 box3">
123
</div>
<h4>
line-height:15px;
border: 1px solid transparent;
box-sizing:border-box;
(就是微调高度)</h4>
<div class="question1 box4">
123
</div>
<h3>文字, 行高, 容器高度为奇数</h3>
<p>
结论: 修改容器高度, 放大缩小法和添加border有效.
</p>
<h4>容器高度从15px 变为16px</h4>
<div class="question2 box5">
123
</div>
<h4>表格居中</h4>
<div class="question2 box1">
<div class="child1">123</div>
</div>
<h4>flex 居中</h4>
<div class="question2 box2">
123
</div>
<h4>数据翻倍, 然后用 scale 缩小</h4>
<div class="question2 box6">
123
</div>
<h4>
line-height:15px;
border: 1px solid transparent;
box-sizing:border-box;
</h4>
<div class="question2 box4">
123
</div>
.normal{
width:200px;
height: 15px;
background: #000;
margin-bottom:10px;
font-size:10px;
line-height:15px;
color:#fff;
font-family: sans-serif;
}
.question1 {
width:200px;
height: 15px;
background: #000;
margin-bottom:10px;
font-size:10px;
line-height:15px;
color:#fff;
font-family: arial;
}
.question2 {
width:200px;
height: 15px;
background: #000;
margin-bottom:10px;
font-size:12px;
line-height:15px;
color:#fff;
font-family: arial;
}
.box1 {
display: table;
}
.child1 {
display: table-cell;
vertical-align: middle;
}
.box2 {
display: flex;
align-items: center
}
.box3 {
width: 400px;
height: 30px;
line-height:30px;
font-size:20px;
transform: scale(0.5);
transform-origin: top left;
}
.box4 {
line-height:15px;
border: 1px solid transparent;
box-sizing:border-box;
}
.box5 {
line-height:16px;
height:16px;
}
.box6 {
width: 400px;
height: 30px;
line-height:30px;
font-size:24px;
transform: scale(0.5);
transform-origin: top left;
}