Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Thay đổi màu placeholder của input với CSS

Để tùy chỉnh màu placeholder, sử dụng pseudo-element ::placeholder và các prefix cho trình duyệt cũ.

Ví dụ mã nguồn

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
  body {
    font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    padding: 20px;
  }
  input {
    font-size: 40px;
    font-weight: bold;
    padding: 10px;
    border: 2px solid #ccc;
    border-radius: 4px;
    width: 100%;
    max-width: 500px;
  }
  /* Chuẩn hiện đại */
  ::placeholder {
    color: rgb(70, 53, 167);
    opacity: 1; /* Firefox đặt opacity < 1 mặc định */
  }
  /* IE 10-11 */
  :-ms-input-placeholder {
    color: rgb(66, 51, 155);
  }
  /* Edge cũ (trước Chromium) */
  ::-ms-input-placeholder {
    color: rgb(122, 69, 182);
  }
</style>
</head>
<body>
<h1>Ví dụ đổi màu Placeholder</h1>
<input type="text" placeholder="Văn bản placeholder ở đây" />
</body>
</html>

Các selector pseudo-element cho placeholder

Trình duyệtSelector
Chrome, Firefox, Safari, Edge (Chromium)::placeholder
IE 10-11:-ms-input-placeholder
Edge cũ (Legacy)::-ms-input-placeholder

Lưu ý quan trọng

  • Opacity: Firefox mặc định opacity ~0.54 cho placeholder. Cần set opacity: 1 để màu hiển thị chính xác
  • Không thể style: font-size, font-weight, padding... trên placeholder (chỉ color, opacity, text-transform, v.v.)
  • :placeholder-shown - Pseudo-class cho input ĐANG HIỂN THỊ placeholder (khác ::placeholder)

Ví dụ :placeholder-shown

input:placeholder-shown { border-color: #ccc; }
input:not(:placeholder-shown) { border-color: green; } /* Đã nhập text */