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