About this snippet

The default file input is awkward to style and renders differently in every browser. This hides it and puts a styled label in front.

Clicking the label opens the file dialog, because that is what a label does when it points at an input. Nothing is faked with JavaScript, so focus order and screen reader announcements behave the way people expect.

A few lines of script write the chosen filename beside the button. Delete them and the button still opens and uploads correctly, you just lose the filename readout.

Size
1.4 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
372
<div class="file-wrapper">
  <input type="file" id="upload" hidden>
  <label for="upload" class="file-btn">
    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
    <span>Choose File</span>
  </label>
  <span id="fileName">No file chosen</span>
</div>
.file-wrapper {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  display: flex;
  align-items: center;
  gap: 12px;
}
.file-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  background: #ffffff;
  border: 1px solid #d1d5db;
  padding: 10px 16px;
  border-radius: 8px;
  cursor: pointer;
  color: #374151;
  font-weight: 500;
  transition: all 0.2s;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}
.file-btn:hover {
  border-color: #3b82f6;
  color: #3b82f6;
  background: #eff6ff;
}
#fileName {
  color: #6b7280;
  font-size: 0.9rem;
}
const fileInput = document.getElementById("upload");
const fileName = document.getElementById("fileName");

fileInput.addEventListener("change", function() {
  if (this.files && this.files.length > 0) {
    fileName.textContent = this.files[0].name;
  } else {
    fileName.textContent = "No file chosen";
  }
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save