最新答案(2014 年 10 月)
在玩耍并观察“参考”项目在做什么之后,我意识到一件事:我们做错了。
简而言之:对于一个可靠且干净的跨浏览器解决方案,不得使用line-height 属性来使input type="text" 元素更高,而是使用padding 属性。
跨浏览器问题
正如问题中所指出的,浏览器以不同方式解释 input type="text" 元素的 line-height 属性。
在这种情况下,对于 2012 年的 Chrome,甚至现在 2014 年 10 月(版本 37),它是针对光标位置的。
请注意,一个相关的错误在 2010 年 6 月提交,https://code.google.com/p/chromium/issues/detail?id=47284,但随后作为过时而关闭(谁知道为什么?):但提供的实时错误复制,http://jsbin.com/avefi/2,在写作(2014 年 10 月 - chrome 37)。
请注意,Valli69 的答案也将line-height 属性确定为问题的根源。但随后使用了一些相当 hacky/dirty/risky 的 IE8 和 IE9 修复(使用 \0/ 和 \9)。关于这些技术的相关问题Ie8 CSS Hack - best method?
不使用line-height 和height 属性怎么办?
这个解决方案很简单,甚至现代和旧的浏览器都支持!
1) 简化示例中的解决方案
/*
* [1] overrides whatever value "line-height" property was given by any other selector
* note: make it "line-height: normal !important;" if necessary
* [2] overrides whatever value "height" property was given by any other selector
* note: make it "height: auto !important;" if necessary
*/
.username {
line-height: normal; /* [1] */
height: auto; /* [2] */
padding-top: 10px;
padding-bottom: 10px;
}
<input class="username" type="text" placeholder="Username" />
http://jsbin.com/yadebenoniro/1/edit?html,css,output 上的现场演示(ps.在 IE8 上使用此 URL http://jsbin.com/fugegalibuha/1 进行测试)
在 Windows 操作系统上测试:IE8+、IE11、Chrome 38 和 Firefox 32。
2) 问题上下文中的解决方案
/*
* [1] overrides whatever value line-height property was given by any other selector
* note: make it "line-height: normal !important;" if necessary
* [2] overrides whatever value "height" property was given by any other selector
* note: make it "height: auto !important;" if necessary
*
* [3] use the padding-top, padding-bottom to adjust the height of your input type text
* [4] keep in mind that when changing the font-size value you will have to adjust the padding top and padding bottom if you want to keep the same height as previously
*/
.username input {
background-color: #FFFFFF;
border: 2px solid #DDDDDD;
border-radius: 5px;
color: #9E9E9E;
height: auto; /* [2] */
line-height: normal; /* [1] */
margin: 15px 0px 0px 0px;
padding: 10px 5px 10px 5px; /* [3] */
width: 330px;
font-size: 20px; /* [4] */
}
http://jsbin.com/busobokapama/1/edit?html,css,output 上的现场演示(ps.在 IE8 上使用此 URL http://jsbin.com/busobokapama/1 进行测试)
在 Windows 操作系统上测试:IE8+、IE11、Chrome 38 和 Firefox 32。
3) 进一步说明
查看Foundation 后,我想到了这个想法:它仅使用height 和padding 属性:line-height 属性保留为默认值浏览器提供值,即line-height: normal。
亲自查看:通过检查 input type="text" 元素 on foundation's form component demo page http://foundation.zurb.com/docs/components/forms.html
唯一的问题是即使“只是”使用height 和padding 对IE8 来说似乎也是一个问题,所以我决定甚至删除height 属性。
结论
这个解决方案显然具有代码简单的巨大优势,可以在所有浏览器中“正常工作”。
但它也有一个缺点,就是不能让您完全控制计算的总高度:计算的高度属性(字体大小 + 任意像素数)+ padding-top + padding-bottom + (border-width x 2)。 “计算高度属性”seems to vary from browsers to browsers,因此 “任意像素数” 命名。
由您决定您最喜欢什么:简单的代码或像素精确的设计。
资源