Pseudo-element ::placeholder cho phép style text placeholder riêng biệt với text nhập vào.
Cú pháp
::placeholder { color: #999; opacity: 1; /* Firefox fix */ }
input::placeholder { ... } /* Chỉ input */
textarea::placeholder { ... } /* Chỉ textarea */
Ví dụ 1: Màu cho input cuối cùng
<!DOCTYPE html>
<html>
<head>
<style>
input { padding: 12px; margin: 10px 0; width: 300px; border: 1px solid #ccc; border-radius: 4px; }
input:last-child::placeholder { color: cornflowerblue; font-style: italic; }
</style>
</head>
<body>
<input type="text" placeholder="Màu mặc định" />
<br>
<input type="text" placeholder="Màu cornflowerblue :D" />
</body>
</html>
Ví dụ 2: Tất cả input cùng màu
<style>
input::placeholder { color: fuchsia; opacity: 1; }
input { margin: 10px; width: 100%; max-width: 400px; padding: 12px; }
.form-box {
display: flex; flex-direction: column;
padding: 20px; border-radius: 12px;
box-shadow: inset 0 0 30px brown; max-width: 500px;
}
</style>
<div class="form-box">
<input type="text" placeholder="Placeholder bình thường" />
<input type="email" placeholder="somenone@somewhere.com" />
<button>Nút giả</button>
</div>
Kết quả
Placeholder màu fuchsia (hồng tím) cho tất cả input, hoặc chỉ input cuối màu cornflowerblue.
Lưu ý cross-browser
- Firefox thêm
opacity: 0.54mặc định → cần setopacity: 1 - IE dùng
:-ms-input-placeholder(deprecated) - Edge cũ:
::-ms-input-placeholder