我正在尝试在Chrome中使用相同的样式设置带有值的文本输入,带有占位符的文本输入和跨度。具体来说,我想独立于字体大小来控制行高。

但是,在输入值上似乎存在某种最小的行高(或引起类似影响的某种东西),这似乎以某种方式将文本压低,从而阻止了相同的样式。

HTML示例:

<div>
  <input type="text" value="Text">
  <input type="text" placeholder="Text">
  <span>Text</span>
</div>

CSS:
div {
  line-height: 50px;
  font-family: Arial;
}

input,
span {
  font-size: 50px;
  line-height: 50px;
  height: 50px;
  width: 100px;
  padding: 0;
  min-height: 0;
  display: inline-block;
  font-family: inherit;
  border: 2px solid red;
  overflow: hidden;
  vertical-align: top;
}

结果可以在

http://plnkr.co/edit/oHbhKDSPTha8ShWVOC7N?p=preview
以下是Linux上的Chrome 44.0.2403.155(64位)的屏幕截图:

html - Chrome上的文字输入:行高似乎最​​小-LMLPHP

奇怪的是,占位符似乎使用所需的行高设置样式,而输入的文本值放置在不同的位置。我现在不关心占位符的颜色。

如何为所有3个元素设置样式,以使文本位于自定义行高的相同位置?

我知道我可以只将line-height设置为normal1.2,或减小字体大小,以使元素相同地显示,但它们不会具有我想要的视觉外观。

最佳答案

我想我已经做到了!!!

在我的测试中,行高似乎必须至少是字体大小的〜115%,因此,如果您想要50px高的元素,则所有内容必须都〜43px:

html - Chrome上的文字输入:行高似乎最​​小-LMLPHP

图1.字体大小的50px行高的86%。事情排队了,但没有遵循OP要求的50px字体大小。

input, span {
    border: 2px solid red;
    display: inline-block;
    font: 43px Arial;
    line-height: 50px;
    padding: 0;
    vertical-align: middle;
	width: 100px;
    outline-style:none;
    box-shadow:none;
    overflow:hidden;
    /* optional - to include the borders in the element size:
    box-sizing:border-box;
    */
}
<input type="text" value="Text">
<input type="text" placeholder="Text">
<span>Text</span>


如果将字体大小增加到所需的50px,则输入框应遵守的最小行高为〜58px。尝试使用垂直对齐方式来抵消此偏移量对输入没有任何影响,但是我们可以固定元素的高度并 overflow hidden 以给出一致的(尽管不是完全值得尊重的)外观:

html - Chrome上的文字输入:行高似乎最​​小-LMLPHP

图2. 50px的文本将行高强制为58px,该行的高度被裁剪,隐藏了溢出。

input, span {
    border: 2px solid red;
    display: inline-block;
    font: 50px Arial;
    line-height: 58px;
    padding: 0;
    height:50px;
    vertical-align: top;
    width: 100px;
    outline-style:none;
    box-shadow:none;
    overflow:hidden;
    /* optional - to include the borders in the element size:
    box-sizing:border-box;
    */
}
<input type="text" value="Text">
<input type="text" placeholder="Text">
<span>Text</span>


关闭,但没有雪茄。但这让我开始思考-也许伪元素的限制不太严格?我发现即使在input::first-line中也可以设置input伪样式的样式,这将尊重高度,字体大小,行高和垂直对齐!

因此,瞧!

html - Chrome上的文字输入:行高似乎最​​小-LMLPHP

图3.赢得胜利的第一线伪元素!

input, span {
    border: 2px solid red;
    display: inline-block;
    font: 50px Arial;
    line-height: 50px;
    height: 50px;
    padding: 0;
    vertical-align: middle;
    width: 100px;
    outline-style:none;
    box-shadow:none;
    overflow:hidden;
    /* optional - to include the borders in the element size:
    box-sizing:border-box;
    */
}
input::first-line, span::first-line {
    vertical-align: middle;
}
/* weirdly the placeholder goes black so we have to recolour the first-line */
input::-webkit-input-placeholder::first-line {
    color:grey;
}
<input type="text" value="Text">
<input type="text" placeholder="Text">
<span>Text</span>


这是很多的jsFiddle,所以您可以看到我的工作。 ;)

https://jsfiddle.net/romz58cc/4/

09-30 19:08
查看更多