How to customize file input type box using CSS and jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the CSS Opacity and Positioning method

By default different browser renders the HTML <input type="file"> differently, also if try to style them with the CSS properties it doesn't work. But, you can use the CSS opacity and position property in combination with the jQuery change() method to create your own custom file upload form control that is consistent across the browsers.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>Custom File Input Field with CSS and jQuery</title>
  • <style type="text/css">
  •     .custom-file-input{
  •         display: inline-block;
  •         overflow: hidden;
  •         position: relative;
  •     }
  •     .custom-file-input input[type="file"]{
  •         width: 100%;
  •         height: 100%;
  •         opacity: 0;
  •         filter: alpha(opacity=0);
  •         zoom: 1;  /* Fix for IE7 */
  •         position: absolute;
  •         top: 0;
  •         left: 0;
  •         z-index: 999;
  •     }
  • </style>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         $('.custom-file-input input[type="file"]').change(function(e){
  •             $(this).siblings('input[type="text"]').val(e.target.files[0].name);
  •         });
  •     });
  • </script>
  • </head>
  • <body>
  •     <form>
  •         <div class="custom-file-input">
  •             <input type="file">
  •             <input type="text">
  •             <input type="button" value="Attach">
  •         </div>
  •     </form>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.