我已经用height:22px;
和line-height:22px;
创建了一个<div>
,以垂直为文本中心。
还有带有height:22px;
的<input>
(输入中的文本自动对齐)。
我注意到垂直对齐方式与某些浏览器不正确,尤其是在移动设备上。
除行高度以外,还有一个替代属性可以垂直居中文本?
以及如何在输入框中正确集中文本?
.myinput{
width: 50px;
height: 22px;
font-size: 9px;
font-family: Arial;
text-align: right;
}
.mydiv{
width: 50px;
height: 22px;
line-height: 22px;
font-size: 9px;
font-family: Arial;
text-align: center;
border: 1px solid black;
}
<input type="text" class="myinput" value="EXAMPLE"/>
<div style="height:10px;"></div>
<div class="mydiv">EXAMPLE</div>
您是否尝试过CSS Flexbox?这是控制父母div中孩子的布局和位置的好方法。您可以在这里了解更多信息:https://css-tricks.com/snippets/css/a-guide-to-flexbox/
.mydiv
和.myinput
下方将在内部水平和垂直居中。
.myinput{
width: 50px;
height: 22px;
font-size: 9px;
font-family: Arial;
text-align: center;
display:flex;
justify-content:center;
align-items:center;
}
.mydiv{
width: 50px;
height: 22px;
font-size: 9px;
font-family: Arial;
text-align: center;
display:flex;
justify-content:center;
align-items:center;
border: 1px solid black;
}
<input type="text" class="myinput" value="EXAMPLE"/>
<div style="height:10px;"></div>
<div class="mydiv">EXAMPLE</div>
有几种方法可以做到 - 也许更新一个问题的问题,您可以看到哪些问题,我们可以最好地找到答案。
类似的东西很容易,应该在大多数浏览器中工作。
.wrapper {
height:22px;
background:#fff;
width: 100px;
text-align:center;
border:1px solid #000;
}
.wrapper:before {
content:"";
height:100%;
display:inline-block;
vertical-align: middle
}
.middle {
display:inline-block;
}
<div class="wrapper">
<div class="middle">Here we go</div>
</div>