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

Tạo kiểu nút tải file (file upload button) với ::file-selector-button


Pseudo-element ::file-selector-button (Firefox) và ::-webkit-file-upload-button (Chrome/Safari/Edge) cho phép style nút chọn file.

Cú pháp

input[type="file"]::file-selector-button { /* Firefox */ }
input[type="file"]::-webkit-file-upload-button { /* WebKit */ }

Ví dụ Firefox

<!DOCTYPE html>
<html>
<head>
  <style>
    input[type="file"]::file-selector-button:hover {
      cursor: grab;
      background-color: blueviolet;
      color: white;
      font-size: 1.2em;
      box-shadow: inset 5px 10px 10px cornflowerblue;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <form>
    <label for="fup">Chọn file</label>
    <input type="file" id="fup" />
    <input type="text" placeholder="Văn bản ngẫu nhiên" />
    <button type="submit">Xong</button>
  </form>
</body>
</html>

Ví dụ Cross-browser (Chrome + Firefox)

<style>
  input[type="file"]::file-selector-button,
  input[type="file"]::-webkit-file-upload-button {
    cursor: pointer;
    background-color: crimson;
    color: white;
    font-size: 1.2em;
    border-radius: 25%;
    box-shadow: inset 5px 10px 10px cornsilk;
    border: none;
    padding: 8px 16px;
    transition: all 0.2s;
  }
  input[type="file"]::file-selector-button:hover,
  input[type="file"]::-webkit-file-upload-button:hover {
    background-color: #c00;
    transform: scale(1.05);
  }
</style>

Lưu ý

  • Firefox hỗ trợ ::file-selector-button chuẩn
  • Chrome/Safari/Edge cần ::-webkit-file-upload-button
  • Không thể style phần text "No file chosen" bên cạnh nút
  • Cách thay thế hoàn toàn: dùng <label> wrapper ẩn input