我有以下输入元素(我故意省略了示例不需要的属性):
<input type="text" style="display: block; height: 40px; font-size: 14px; line-height: 40px"/>
在 Chrome 和 Internet Explorer(可能还有 Opera)中,输入中的任何文本都将垂直居中。然而,Firefox 似乎忽略了这个声明。将其设置为 display: inline-block;
或使用 vertical-align: middle;
在 Firefox 中无效。
我还尝试将顶部和底部填充设置为 13px
,将高度设置为 14px
,这(结合字体大小)将导致元素 40px
高。这按预期工作;除了任何带尾部的字符(如 g、q、j 等)在底部被截断。
我正在寻找一种跨浏览器的解决方案,用于在具有固定高度的输入框中垂直对齐文本。 input 元素将有自己的悬停和焦点样式,因此通过将元素本身垂直放置在 40px
高的空间中来伪装居中并不是真正的选择。
干杯
最佳答案
I've also tried setting the top & bottom paddings to 13px, and the height to 14px, which (combined with the font-size) will result in an element 40px tall. This works as expected; except any characters with tails (like g, q, j etc) are cut off at the bottom.
如何仅将顶部填充设置为 13px(而不是底部填充)并将高度设置为剩余空间,如下所示:
<input type="text" style="display: block; height: 27px; padding-top: 13px; font-size: 14px">
它在 Firefox 和 Chrome 中都按预期工作;我目前无法访问 IE,但我相信它也能在 IE 中运行。
关于css - 输入元素中的文本垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2222019/