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

เปลี่ยนสี placeholder ของช่องกรอกข้อความด้วย CSS


ใช้ pseudo-element ::placeholder เพื่อเปลี่ยนสีข้อความ placeholder ในช่องกรอกข้อความ

ไวยากรณ์

::placeholder { attribute: /*value*/ }

ตัวอย่างที่ 1: เปลี่ยนสีเฉพาะช่องกรอกลำดับคู่

<!DOCTYPE html> <html> <head> <style> input:last-child::placeholder {    color: cornflowerblue; } </style> </head> <body> <input type="text" placeholder="Default color" /> <input type="text" placeholder="Check my new color :D" /> </body> </html>

ตัวอย่างที่ 2: เปลี่ยนสี placeholder ทุกช่องกรอกพร้อมจัดเลย์เอาต์ด้วย Flexbox

<!DOCTYPE html> <html> <head> <style> input::placeholder {    color: fuchsia; } input {    margin: 2%;    width: 100%; } div {    display: flex;    flex-direction: column;    margin: 3%;    padding: 3%;    text-align: center;    align-items: center;    box-shadow: inset 0 0 30px brown; } button {    width: 40%; } </style> </head> <body> <div> <input type="text" placeholder="Normal placeholder" /> <input type="email" placeholder="somenone@somewhere.com" /> <button>dummy btn</button> </div> </body> </html>

หมายเหตุ: ::placeholder รองรับในเบราว์เซอร์สมัยใหม่ทั้งหมด แต่เก่าๆ อาจต้องใช้ prefix เช่น ::-webkit-input-placeholder, ::-moz-placeholder, :-ms-input-placeholder