Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

การจัดสไตล์ฟอร์มด้วย CSS Attribute Selectors

Attribute Selectors: เลือก Element ตาม Attribute/Value

CSS Attribute Selectors เลือก element โดยดู attribute แทน class/id เหมาะกับ Form styling (input types) หรือ dynamic attributes

Attribute Selector Patterns

Selectorคำอธิบาย
[attr]มี attribute นี้ (ไม่สน value)
[attr="value"]attribute เท่ากับ value อย่างแม่นยำ
[attr~="value"]attribute มีคำว่า value (space-separated)
[attr|="value"]attribute เริ่มต้นด้วย value- หรือเท่ากับ value
[attr^="value"]attribute เริ่มต้นด้วย value
[attr$="value"]attribute จบด้วย value
[attr*="value"]attribute มี value อยู่ตรงไหนก็ได้
[attr="value" i]Case-insensitive (flag i)

โค้ดตัวอย่าง: Style Form ตาม Input Type

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    input[type="text"] {
      width: 300px; display: block; margin-bottom: 10px;
      background-color: rgb(195, 250, 247); font-size: 18px; padding: 15px; border: none;
    }
    input[type="submit"] {
      padding: 10px; font-size: 18px; border: none; outline: none;
      background-color: rgb(75, 163, 16); color: white; cursor: pointer;
    }
    input[type="password"] {
      width: 300px; padding: 10px; background-color: red; color: white; border: none;
    }
  </style>
</head>
<body>
  <h1>CSS Attribute Selector Example</h1>
  <form>
    <label for="fname">First name:</label><br />
    <input type="text" id="fname" name="fname" value="Ron" />
    <label for="lname">Last name:</label><br />
    <input type="text" id="lname" name="lname" value="Shaw" />
    <label for="pass">Password:</label><br />
    <input type="password" id="pass" name="pass" value="password" />
    <input type="submit" value="Submit" />
  </form>
</body>
</html>

ประยุกต์ใช้งาน

  • a[target="_blank"]::after { content: " ➚"; } – ไอคอนลิงก์เปิดแท็บใหม่
  • img[alt=""] { border: 2px solid red; } – Highlight รูปไม่มี alt
  • input[required] { border-left: 3px solid red; } – Required field indicator
  • [dir="rtl"] .icon { transform: scaleX(-1); } – Flip icon สำหรับ RTL

Specificity

Attribute selector มี specificity เท่ากับ class (0,1,0) สูงกว่า element (0,0,1) ต่ำกว่า ID (1,0,0)