好吧,这似乎是不可能正确的.我有一个文本框和一个 Select 框.我希望它们的宽度完全相同,所以它们在左边缘和右边缘对齐.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
input, select {
width: 200px;
}
</style>
</head>
<body>
<input type="text" value="ABC"><br>
<select>
<option>123</option>
</select>
</body>
</html>
你觉得这样就行了,对吧?不是的.在Firefox中, Select 框要短6px.请参见屏幕截图.
好的,让我们编辑代码,制作两种样式.
<style type="text/css">
input {
width: 200px;
}
select {
width: 206px;
}
</style>
好的,这样就行了!
哦,等等,最好在Chrome上测试一下...
有人能告诉我如何在所有浏览器中排列这些吗?为什么我不能只做宽度:200px,为什么所有的浏览器都有不同的显示方式?另外,既然我们这样做了,为什么文本框和 Select 框的高度不同呢?我们怎么才能让他们达到同样的高度呢?已经try 过高度和线条高度,但都无济于事.
解决方案:
好的,我已经从下面的答案中找到了解决方案.关键是使用box-sizing: border-box属性,这样当您指定includes的宽度时,边框和填充.请参见excellent explanation here.那么浏览器就不能把它填满了.
下面是代码,还将框的高度设置为相同的大小,并缩进框内的文本,使其对齐.你还需要设置边框,因为Chrome有一个非常奇怪的边框,它用于 Select 框,这会抛出对齐.这将适用于HTML5站点(例如,支持IE9、Firefox、Chrome、Safari、Opera等).
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
input, select {
width: 200px;
border: 1px solid #000;
padding: 0;
margin: 0;
height: 22px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
input {
text-indent: 4px;
}
</style>
</head>
<body>
<input type="text" value="ABC"><br>
<select>
<option>123</option>
<option>123456789 123123123123</option>
<option>123456789 123123123123 134213721381212</option>
</select>
</body>
</html>
最后一个警告,您可能不希望输入按钮、复选框等包含在此样式中,因此使用input:not([type='button'])
不将其应用于某些类型,或使用input[type='text'], input[type='password']
指定您希望应用的类型.