How to Create a Custom File Input With Preview Using HTML, CSS, and JavaScript
Default file input elements are notoriously difficult to style and often don’t provide the best user experience. In this tutorial, we’ll build a custom file input component that lets users select an image and preview it before uploading — using plain HTML, CSS, and JavaScript.
Step 1: Basic HTML Structure
We'll start with a file input and a placeholder for the preview:
<div class="file-upload"> <input type="file" id="fileInput" accept="image/*" hidden /> <label for="fileInput" class="upload-label">Choose an Image</label> <div id="preview" class="preview-area"></div> </div>
Step 2: Add CSS Styling
We’ll style the label to look like a button and make the preview area clean and responsive.
<style> .upload-label { display: inline-block; padding: 10px 20px; background-color: #2563eb; color: white; cursor: pointer; border-radius: 6px; font-weight: bold; } .preview-area { margin-top: 15px; } .preview-area img { max-width: 100%; max-height: 300px; display: block; border: 1px solid #ccc; border-radius: 6px; } </style>
Step 3: Add JavaScript for Image Preview
Now we'll add the logic to display a preview when a file is selected.
<script> const fileInput = document.getElementById('fileInput'); const preview = document.getElementById('preview'); fileInput.addEventListener('change', () => { const file = fileInput.files[0]; if (file && file.type.startsWith('image/')) { const reader = new FileReader(); reader.onload = (e) => { preview.innerHTML = '<img src="' + e.target.result + '" alt="Image preview">'; }; reader.readAsDataURL(file); } else { preview.innerHTML = ''; } }); </script>
Conclusion
Custom file inputs with previews are a great way to improve UX. This approach gives users confidence that they’ve selected the correct file — and it looks a lot better than the default input!
If this post helped you, consider supporting me: buymeacoffee.com/hexshift
Top comments (0)