在 inline style 中寫 style="background:url(0); border-width:0" 會導致輸入框背景變透明(無背景色),原因在於 background 簡寫屬性會重置所有背景相關子屬性,包含 background-color。
background 是簡寫屬性,包含:
background-colorbackground-image (url())background-repeatbackground-positionbackground-attachmentbackground-sizebackground-originbackground-clip當設定 background: url(0) 時,瀏覽器解析為:
background-image: url(0); background-color: transparent; background-repeat: repeat; ...
未指定的子屬性會重置為初始值,因此 background-color 變為 transparent(透明)。
url(0) 會被視為相對路徑指向名為 "0" 的檔案,大多數情況下會發生 404 錯誤,等同於無背景圖片。這不是「無背景」的特殊語法。
| 需求 | 正確寫法 |
|---|---|
| 僅設定背景圖片,保留原背景色 | background-image: url(0); 或 background: url(0) no-repeat center / cover;(不重置 color) |
| 移除背景圖片,保留背景色 | background-image: none; |
| 同時設定圖片與顏色 | background: #fff url(bg.png) no-repeat center; |
| 輸入框無背景、無邊框 | background: transparent; border: none; |
MDN CSS background 完整規格:簡寫屬性會重置未指定的子屬性。