Toggle navigation
☰
Home
HTML
CSS
Scripting
Database
<!DOCTYPE html> <title>My Example</title> <style> .file-upload-container { max-width: 500px; margin: 40px auto; font-family: sans-serif; padding: 30px; background-color: #f8f9fa; border-radius: 8px; border: 1px solid #e0e0e0; } .file-upload-container h3 { margin-top: 0; text-align: center; } /* -- The core styles -- */ /* Use Flexbox for robust layout control */ .file-upload-group { display: flex; align-items: center; gap: 15px; /* Creates space between the button and the text */ } /* Visually hide the file input, but it's still accessible via its label */ .file-upload-input { width: 1px; height: 1px; opacity: 0; overflow: hidden; position: absolute; z-index: -1; } /* This is the <label> that we style to look like a button */ .file-upload-label { background-color: #34495e; color: white; padding: 10px 20px; border-radius: 5px; cursor: pointer; font-weight: 500; transition: background-color 0.2s; white-space: nowrap; flex-shrink: 0; /* Prevents the button from shrinking */ } .file-upload-label:hover { background-color: #2c3e50; } /* Keyboard focus style for the label "button" */ .file-upload-label:focus { outline: 2px solid #007bff; outline-offset: 2px; } /* This is the <span> where we display the file name */ .file-name-display { font-size: 0.9rem; color: #555; font-style: italic; /* These properties ensure the text doesn't get cut off */ flex-grow: 1; /* Allows it to take up remaining space */ min-width: 0; /* Allows flex items to shrink properly */ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } </style> <div class="file-upload-container"> <h3>Upload Your Document</h3> <form action="#" method="post" enctype="multipart/form-data"> <div class="file-upload-group"> <input type="file" id="custom-file-upload" class="file-upload-input" name="document" accept=".pdf, .doc, .docx, .txt"> <label for="custom-file-upload" class="file-upload-label" tabindex="0">Choose File...</label> <span class="file-name-display" id="file-chosen">No file selected</span> </div> </form> </div> <!-- ** JAVASCRIPT ** --> <script> const customFileInput = document.getElementById('custom-file-upload'); const fileChosenDisplay = document.getElementById('file-chosen'); const fileUploadLabel = document.querySelector('.file-upload-label[for="custom-file-upload"]'); if (customFileInput && fileChosenDisplay && fileUploadLabel) { // Update display text when a file is chosen customFileInput.addEventListener('change', function(){ fileChosenDisplay.textContent = this.files.length > 0 ? this.files[0].name : 'No file selected'; }); // Add keyboard accessibility: allow 'Enter' or 'Space' to trigger the file input fileUploadLabel.addEventListener('keydown', function(e) { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); // Prevent default button behavior customFileInput.click(); // Programmatically click the hidden file input } }); } </script>