使用CSS垂直对齐输入占位符(或设置行高)

4
有没有可能将占位符在父输入框之外垂直居中对齐?在下面的代码中,似乎没有办法使占位符出现在输入框的垂直中心。我已经尝试了我能想到或在线找到的所有CSS属性和解决方法,但输入框和占位符上不同的字体大小似乎使它在至少在Webkit浏览器中无法实现。
编辑:左边是问题,右边是期望的外观: enter image description here

input {
  font-size: 22px;
  text-align: center;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  font-size: 9px;
  text-transform: uppercase;
  color: #AAA;
}
<input type='text' placeholder='enter some text' />


可能是居中HTML输入文本字段占位符的重复问题。 - Chang
4
@Chang. 它们完全不同。 - cronoklee
将输入的行高和字号设置为相同对我来说很有效。 - Robin
2个回答

13

最好的解决方案可能是在占位符 CSS 规则中简单地添加 translate3d 转换,如下所示:

最佳解决方法可能是在占位符 CSS 规则中添加translate3d转换,如下所示:

input {
  font-size: 22px;
  text-align: center;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  font-size: 9px;
  text-transform: uppercase;
  color: #AAA;
  transform:translate3d(0,-4px,0)
}
<input type='text' placeholder='enter some text' />


7
这似乎是一个很愚蠢的“解决方案”,但也许你可以在::-webkit-input-placeholder中用transform:scale(0.45)替换font-size: 9px;。这个方法似乎可以在任何支持::-webkit-input-placeholder的地方使用。

input {
  font-size: 22px;
  text-align: center;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  text-transform: uppercase;
  color: #AAA;
  transform: scale(0.45);
}
<input type='text' placeholder='enter some text' />

编辑:左对齐

input {
  font-size: 22px;
  text-align: left;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  text-transform: uppercase;
  color: #AAA;
  transform: scale(0.45);
  transform-origin: 0% 50%;
}
<input type='text' placeholder='enter some text' />


哦,我喜欢它!如此巧妙,看起来完美!谢谢你!! - cronoklee
@cronoklee 哈哈,很高兴你对此感到满意。但这让我感觉很不舒服。 - Joseph Marikle
不知道你怎么看,但它并没有垂直居中,或者我应该这样说,它无法实现。 - VXp
1
@cronoklee 可以通过微调实现。只需将转换设置为左中心,使用 transform-origin: 0% 50%; 即可。 - Joseph Marikle
好的,作为一个新答案发布。再次感谢你的帮助,伙计。 - cronoklee
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接