表單元素外觀千篇一律,是很多設計稿落地時的痛點。屬性選擇器提供了一個乾淨的解法:直接依 type 屬性區分控制項,不必為每個元素額外加上 class。
只要寫成 input[type="text"] 這樣的形式,就能精準命中特定類型的控制項:
input[type="text"] { background-color: #FFC; }
input[type="password"] { background-image: url(BG.gif); }
input[type="submit"] { background-color: blue; color: white; }
input[type="reset"] { background-color: navy; color: white; }
input[type="button"] { background-color: lightblue; }
單選按鈕與核取方塊也可以調整間距:
input[type="radio"] { margin: 10px; }
input[type="checkbox"] { margin: 10px; }
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>屬性選擇器範例</title>
<style type="text/css">
input[type="text"] { background-color: #FFC; }
input[type="password"] { background-image: url(BG.gif); }
input[type="submit"] { background-color: blue; color: white; }
input[type="reset"] { background-color: navy; color: white; }
input[type="radio"] { margin: 10px; }
input[type="checkbox"] { margin: 10px; }
input[type="button"] { background-color: lightblue; }
</style>
</head>
<body>
<dl>
<dt>一般文字框:<dd><input type="text" name="" />
<dt>密碼框:<dd><input type="password" name="" />
<dt>送出按鈕:<dd><input type="submit" />
<dt>重設按鈕:<dd><input type="reset" />
<dt>單選:<dd><input type="radio" name="g1" /> <input type="radio" name="g1" />
<dt>核取:<dd><input type="checkbox" name="g2" /> <input type="checkbox" name="g2" />
<dt>普通按鈕:<dd><input type="button" value="button" />
</dl>
</body>
</html>
第一,屬性選擇器在 IE6 完全不支援。以今天的專案來說這早已不是問題,但若你需要回顧當時的相容方案,通常得靠 expression 或額外 class 來補。
第二,radio 與 checkbox 的樣式受限於作業系統。像 background-color 這類屬性在部分瀏覽器上不會生效,能改的多半只有 margin、outline 這類外圍屬性。真正要完全自訂這兩種控制項,得靠偽元素搭配 appearance: none。