When designing web forms, you may come across the need to customize the look and feel of the default file input. The standard file input field usually comes with a “Choose File” button and a label that displays “No file chosen” or the name of the chosen file. However, this default styling might not align with your site’s design.
In this blog post, we’ll guide you through customizing this field using just CSS and JavaScript, without altering the base HTML or needing additional frameworks.
Firstly, ensure your HTML structure is similar to this:
<div class="custom-file-upload"> <label for="uploadField">Upload Your File</label> <input type="file" id="uploadField" name="fileUpload" class="hidden-file-input"> </div>
Note: We’ve wrapped the input field inside a div
to ensure better control over the positioning of elements.
You’ll want to start by hiding the default file input. This ensures that our custom design isn’t interrupted by the browser’s default design:
.hidden-file-input { opacity: 0; position: absolute; z-index: -1; }
Now, let’s add some CSS to style a custom button that will trigger the hidden file input:
.hidden-file-input + label { display: block; padding: 8px 12px; cursor: pointer; background-color: #eee; border: 1px solid #ccc; border-radius: 4px; margin-top: 10px; }
For feedback, users should be able to see the name of the file they’ve selected. Add another styled element for this:
.file-name-display { display: block; margin-top: 8px; font-style: italic; }
We’ll use JavaScript to update the name of the chosen file, and to create and manage our custom button and file display:
document.addEventListener('DOMContentLoaded', function() { const fileInput = document.querySelector('.hidden-file-input'); // Create and insert custom label/button const customLabel = document.createElement('label'); customLabel.setAttribute('for', fileInput.id); customLabel.innerText = 'Choose File'; fileInput.parentNode.insertBefore(customLabel, fileInput.nextSibling); // Create and insert div for file name display const fileNameDisplay = document.createElement('div'); fileNameDisplay.classList.add('file-name-display'); fileNameDisplay.innerText = 'No file chosen'; customLabel.parentNode.insertBefore(fileNameDisplay, customLabel.nextSibling); fileInput.addEventListener('change', function() { const fileName = fileInput.value.split('\\').pop(); fileNameDisplay.innerText = fileName || 'No file chosen'; }); });
With these steps, you’ve successfully transformed the default file input into a customized version that aligns better with your design preferences. This approach offers flexibility, allowing you to adjust the look and feel of the file input field while preserving its core functionality.