Pseudo-class :placeholder-shown` chọn input đang hiển thị placeholder (chưa nhập gì). Dùng để style khác biệt khi rỗng vs đã nhập.
Ví dụ 1: Border màu theo placeholder
<!DOCTYPE html>
<html>
<head>
<style>
input {
padding: 12px 16px;
margin: 10px;
border: 2px solid #ccc;
border-radius: 8px;
font-size: 16px;
width: 300px;
transition: border-color 0.2s;
}
input:placeholder-shown {
border-color: dodgerblue;
background: #f0f8ff;
}
input:nth-of-type(2):placeholder-shown {
border-color: olivedrab;
background: #f0fff0;
}
input:not(:placeholder-shown) {
border-color: #28a745;
background: #f8fff8;
}
</style>
</head>
<body>
<input type="text" placeholder="Nhập tên (border xanh dương)">
<br>
<input type="email" placeholder="Nhập email (border xanh lá)">
<br>
<input type="text" placeholder="Đã có giá trị" value="Đã nhập">
</body>
</html>
Ví dụ 2: Label float animation
<style>
.form-group { position: relative; margin: 30px 0; }
.form-group input {
width: 100%; padding: 15px 10px 5px;
border: none; border-bottom: 2px solid #ccc;
font-size: 16px; background: transparent;
}
.form-group label {
position: absolute; top: 12px; left: 10px;
color: #999; font-size: 16px; pointer-events: none;
transition: all 0.2s ease;
}
.form-group input:placeholder-shown + label { top: 12px; font-size: 16px; }
.form-group input:not(:placeholder-shown) + label,
.form-group input:focus + label {
top: -10px; font-size: 12px; color: #007bff; font-weight: bold;
}
</style>
<div class="form-group">
<input type="text" placeholder=" ">
<label>Họ tên</label>
</div>
Kết quả
- Input rỗng: border xanh, nền nhạt
- Input đã nhập: border xanh lá, nền trắng
- Label float lên khi focus hoặc đã nhập (placeholder rỗng " ")
Lưu ý
:placeholder-shown chỉ hoạt động khi có attribute placeholder. Nếu placeholder="" rỗng, vẫn coi là "shown".