第1张图是chrome模拟器里的效果。
第2、3张图是两台手机里的效果。
第4张图是按钮的样式。
按钮的高度和行高相等,文字应该垂直居中。
第1张图chrome模拟器中是正确的,第2张图中的效果也基本正常,但第3张图中的文字明细偏上了。
单位试过 rem,也试过 px,都会存在这种情况。
有没有人能分析一下问题的原因?
有没有完全兼容的解决方案?
明确一下我的问题:一行文字,在该行垂直方向居中,PC端正常,移动端有的正常,但有的没有垂直居中,这个问题是怎么产生的,有没有解决方案?
默认长宽字体大小先扩大为两倍,再用 scale 缩小为一半大小后的结果,效果确实好了一点,但感觉还是有一点点偏上。
目前比较有效的解决方法就是transform,放大一倍再缩小一半,但是写起来繁琐而且影响布局。我也想知道有没有什么既好又方便的方法
display:-webkit-flex;
justify-content:center;
align-items:center;
width:100px;
height:28px;
模拟器模拟出来的是垂直居中的没错,但是在实际手机中,苹果手机渲染出来是垂直居中的,安卓手机渲染出来就是会偏上一些,兼容的方法就是不要设置height,line-height设置为1,用padding值上下相等来保持垂直居中。
你可以试试vertical-align,另外,没有代码别人不好回答,你可以用codepen做在线demo,方便回答者
1.表格方法:
实现方法:表格内容本来就是垂直居中的,可以通过模拟表格处理。
<div class="box_center">
<div class="inner"></div>
</div>
.box_center {
display: table-cell;
width: 300px;
height: 300px;
text-align: center;
vertical-align: middle;
}
.box_center .inner {
display: inline-block;
}
2.vertical-align: middle
实现方法:利用空元素占位实现
<div class="box_center">
<div class="placeholder"></div>
<div class="inner"></div>
</div>
.box_center {
width: 300px;
height: 300px;
text-align: center;
}
.box_center .inner {
display: inline-block;
}
.box_center .placeholder {
display: inline-block;
width: 0;
height: 100%;
vertical-align: middle;
}
3.绝对定位
.box_center {
width: 300px;
height: 300px;
background: #ccc;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
4.使用 transform 实现
.box_center {
position: absolute;
width: 300px;
height: 300px;
background: #ccc;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
兼容性:Android2.3 系统浏览器不支持容器直接使用 fixed 进行定位,外加 fixed 容器可解决。
结论:
推荐transform 实现
你的line-height改30px试试
用flex布局,几句代码就搞定垂直居中了。教程搜一下就有了
line-height和vertical-align一起使用才更配哦