萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS input 樣式跨瀏覽器統一實戰:高度、垂直置中、字體繼承

攻克 input 跨瀏覽器樣式差異:三大核心技巧

<input type="text"> 在 Firefox/Chrome/Safari/IE 中預設高度、垂直對齊、字體繼承皆不同,導致搜尋框、登入框難以統一。本文提供實測有效的統一方案。

瀏覽器預設差異實測(無任何 CSS 時)

瀏覽器type=text 高度type=text 寬度type=submit 高度type=submit 寬度
Firefox22px146px23px75px
Safari22px146px21px73px
IE24px146px25px73px

三大統一關鍵

  1. 不要設 height,改用 padding 控制高度
    設定 height 會導致 IE 文字貼左上,無法垂直置中。正確做法:padding: 6px 8px; 由內距撐開高度,IE 文字同步置中。
  2. 明確聲明 font-family 與 font-size
    input 不繼承父層字體。必須直接設定:font-family: inherit; font-size: 100%; 或指定具體字體堆疊。
  3. width 與 padding 配合背景圖尺寸
    使用背景圖(如搜尋框圖示)時,確保 width + padding 總寬高與圖片一致,避免文字遮蓋圖示或留白過大。

完整範例:統一搜尋框

.search-input {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 6px 30px 6px 10px; /* 右側留空給搜尋圖示 */
  font-family: "Microsoft JhengHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 14px;
  line-height: 1.5;
  width: 220px;
  background: url(search-icon.svg) no-repeat right 8px center;
  box-sizing: border-box; /* 含 padding 在 width 內 */
}
.search-input:focus { outline: none; border-color: #0066cc; box-shadow: 0 0 0 2px rgba(0,102,204,.2); }

補充:現代瀏覽器統一基準

現代專案建議在 Reset 階段加入:

input, textarea, select, button {
  font-family: inherit;
  font-size: 100%;
  line-height: 1.15;
  margin: 0;
}
input[type="search"] { -webkit-appearance: none; appearance: none; } /* 移除 Safari 圓角 */

掌握這三大關鍵,input 跨瀏覽器樣式不再是噩夢。

copyright © 萬盛學電腦網 all rights reserved