DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS進階教程
用屬性選擇器 input[type] 精準控制表單樣式
編輯:CSS進階教程     

表單元素外觀千篇一律,是很多設計稿落地時的痛點。屬性選擇器提供了一個乾淨的解法:直接依 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。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved