萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

CSS 解決 IE6/IE7 input 按鈕背景圖片黑邊框問題

在 IE6/IE7 中,給 `` 設置背景圖片並保留 `border` 會出現難看的**黑色邊框**。本文提供三種徹底解決方案,兼容現代瀏覽器。

現象重現

<style>
.hk { height:22px; border:#999 1px solid; background:#E5E5E5 url(btn.png) repeat-x; cursor:pointer; }
</style>
<input type="submit" value="登陸" class="hk" style="width:70px" />

IE6/7 顯示:按鈕四周出現 1px 黑框,破壞視覺一致性。

方案一:移除 border,將邊框融入背景圖(最簡單)

.hk { 
    height: 22px; 
    border: none;               /* 關鍵:去除原生 border */
    background: url(btn_with_border.png) no-repeat; /* 背景圖已含邊框 */
    cursor: pointer;
}
  • 優點:零 Hack,所有瀏覽器一致。
  • 缺點:每種寬度/狀態需單獨切圖,維護成本高。

方案二:Label 包裹法(推薦:保留 CSS 邊框靈活性)

<style>
.pn { height:22px; border:none; background:#E5E5E5 url(pn.png) repeat-x; cursor:pointer; }
.l_pn { display:inline-block; *display:inline; *zoom:1; border:#999 1px solid; } /* IE6/7 inline-block Hack */
</style>

<label class="l_pn" style="width:70px">
    <input type="submit" value="登陸" class="pn" style="width:70px" />
</label>
  • 原理:`` 去 border → 無黑框;外層 `
  • 點擊 Label 觸發 Input 點擊(原生行為),無需 JS。
  • IE6/7 需 `

方案三:CSS Hack 針對性隱藏 border(不推薦,維護性差)

.hk { 
    border: 1px solid #999; 
    _border: none;        /* IE6 忽略 */
    *border: none;        /* IE7 忽略 */
    border: 1px solid #999\9; /* IE8+ 保留 */
}

缺點:Hack 混亂,易隨瀏覽器更新失效。

現代最佳實踐:`

<button class="btn" type="submit">登陸</button>

.btn {
    position: relative;
    border: 1px solid #999;
    background: #E5E5E5 url(pn.png) repeat-x;
    padding: 0 12px;
    height: 28px;
    line-height: 26px; /* 垂直居中 */
    cursor: pointer;
    overflow: visible; /* IE 修正內邊距 */
}
/* 移除 IE 內部神秘 padding */
.btn::-moz-focus-inner { border: 0; padding: 0; }
  • `
  • 無 IE 黑框問題,無需 Hack。
  • 語義更正確(表單提交按鈕)。

總結建議

  1. **新項目**:直接用 `
  2. **必須維護 IE6/7**:採用 **Label 包裹法**,平衡靈活性與兼容性。
  3. **極簡場景**:背景圖融合邊框(方案一)。

徹底理解 IE 表單控件渲染機制,才能在兼容性與可維護性間做出最優權衡。

copyright © 萬盛學電腦網 all rights reserved