IE和FireFox在显示按钮时,具有不同的行为。这个行为在单独使用按钮时表现不太明显,但是当把一个很大的按钮放置到另外一个更小的包容元素时候,就表现的特别明显。比如放置到一个div元素当中,如下所示:
<html>
<head>
<style>
.buttonContainer {
position:absolute;
overflow:visible;
}
.backbutton {
font-size: 20px;
font-family: Arial;
font-weight: bold;
font-style: normal;
font-variant: normal;
}
</style>
</head>
<body>
<div id="widget1" class="buttonContainer" style="left: 4px; top: 48px; width: 31px; height: 11px; z-index: 1; cursor: pointer; border: 1px solid red;">
<div style="height: 100%; width: 100%; border: 1px solid green;">
<button style="height: 100%; width: 100%;" class="backbutton">Back</button>
</div>
</div>
<div id="widget2" class="buttonContainer" style="left: 4px; top: 100px; width: 31px; height: 11px; z-index: 1; cursor: pointer; border: 1px solid red;">
<div style="height: 100%; width: 100%; border: 1px solid green;">
<input type="button" value="Back" style="height: 100%; width: 100%;" class="backbutton"/>
</div>
</div>
</body>
</html>
在FireFox和IE上分别执行上述代码后的结果如下:
IE FireFox
可以看到,虽然按钮的高度都设置为相对于包容元素的100%,但是在IE中按钮自动撑高了包容元素,而在Firefox中,按钮超出包容元素的部分被截断了。
为了解决上述问题,可以将按钮的高度设置为auto,如下所示:
<button style="height: auto; width: 100%;" class="backbutton">Back</button>
<input type="button" value="Back" style="height: auto; width: 100%;" class="backbutton"/>
在FireFox和IE上分别执行上述代码后的结果如下:
IE FireFox
此时,当包容元素没有设置边框时候,IE和FireFox的显示效果就比较类似了。
另外,FireFox中的按钮看起来总是比用其他方式模拟的按钮大(比如A标签),也比IE中的按钮大,原因是FireFox的按钮中有一个伪元素(Pseudo-elements),可能用来当按钮获得焦点时候,显示按钮的虚边框。而这个伪元素会占据额外的高度和宽度。如Fix Firefox Button Padding中描述的,我们可以通过设置特定于Firefox的css来解决这个问题。
/* Used within FF chrome to target CSS to specific URLs: being FF-specific,
it is also useful for targeting FF-only code */
@-moz-document url-prefix(http://) {
button::-moz-focus-inner, input[type="button"]::-moz-focus-inner, input[type="submit"]::-moz-focus-inner, input[type="reset"]::-moz-focus-inner {
padding: 0 !important;
border: 0 none !important;
}
}
有时候,上述设置过后,仍然会发现按钮比其他模拟元素大,此时可以像Firefox Button Height Fix中描述的一样,根据页面具体情况,设置按钮的margin属性如下:
input::-moz-focus-inner {
border: 0;
padding: 0;
margin-top:-2px;
margin-bottom: -2px;
}
另外为了使各个浏览器中的按钮显示尽量一致,我们可以设置按钮的overflow属性为visible,width属性为auto,如Styling HTML Submit Buttons中描述的:
.submit {
cursor:pointer;
overflow:visible; /* ie6/7 width fix */
width:auto; /* ie6/7 width fix */
padding:1px 5px;
background:#ddd;
color:#333;
font:10pt arial, sans-serif;
border:1px solid #aaa;
}
我们也可以全部使用图片按钮来代替普通按钮,如-moz-focus-inner中描述的。但是当需要国际化时候,则需要很多的图片来支持不同的语言,这个显然不太合适。
其他比较有意思的关于按钮和CSS的文章:
15 css tricks that must be learned