Styling a dynamic file input to upload a file

Styling a dynamic file input to upload a file

Introduction: When designing web forms, one common challenge is styling the file input button. By default, browsers provide a basic file input element that doesn't match the style of the rest of the form. In this article, we'll explore and learn how to style a file input button in HTML using CSS and Javascript to create a more visually appealing design.

Problem statement: We want the input field(upload file input) to look like a button.

The Default File Input Button: Before we dive into styling, let's take a look at the default appearance of a file input button in HTML. When you add an input element with type="file" to your form, it renders as a button with a text label that says "Choose File" or similar, depending on the browser.

Styling the File Input Button: To style the file input button, we can't directly apply styles to the input element itself. Instead, we'll use a label element as a wrapper and style it to look like a button. Here's how:

 <form>
  <label for="fileUpload" class="form-label">Import investment letter</label>
  <input type="file" id="fileinput"  accept=".doc, .docx, .pdf"  @change="handleFileChange"/>
</form>

Now, let's style the label to resemble a button using CSS:

input[type="file"]::file-selector-button {
  border: 2px solid #CC9933;
  padding: 0.2em 0.4em;
  border-radius: 0.2em;
  background-color: #CC9933;
  transition: 1s;
  color:white;
}
document.getElementById('fileInput').addEventListener('change', function() {
  var label = document.querySelector('.fileInputLabel');
  if (this.files && this.files.length > 0) {
    label.textContent = 'Uploaded';
  } else {
    label.textContent = 'Upload File';
  }
});

we've applied styles to the label element to give it a button-like appearance. We've set padding, background color, border, border radius, and cursor properties to make it look visually appealing, and also a script to make the file when uploaded visible.

Conclusion: We just successfully styled an input field, that looks like a button and files can be uploaded on.