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

วิธีสไตล์ Input Placeholder Text ด้วย CSS

เพื่อสไตล์ placeholder text ของ HTML input element ด้วย CSS ต้อง target pseudo-element attribute ด้วย CSS pseudo selector ::

Input element ธรรมดาพร้อม placeholder text

<input type="text" placeholder="Hello there!">

Placeholder text ด้วย default browser styling:

วิธีสไตล์ Input Placeholder Text ด้วย CSS

CSS

ใช้ CSS ::placeholder selector ทำให้ placeholder text สีแดง:

input::placeholder { color: red; }

ผลลัพธ์:

วิธีสไตล์ Input Placeholder Text ด้วย CSS

Reusable Placeholder Text Class

ไม่อยากสไตล์ทุก <input> เหมือนกัน ใช้ class:

.custom-input-placeholder::placeholder { color: red; }

เพิ่ม class ให้ input ที่ต้องการ:

<input class="custom-input-placeholder" type="text" placeholder="Hello there!">

ข้อมูลเพิ่มเติม

别把 pseudo-elements กับ pseudo-classes สับสน

  • pseudo-elements = ส่วนหนึ่งของ DOM
  • pseudo-classes = state ของ element จาก user interaction เช่น :focus, :active

Syntax difference:

  • pseudo-elements = double colon: ::
  • pseudo-classes = single colon :