Styling an input type=“file” button

后端 未结 30 1660
终归单人心
终归单人心 2020-11-21 11:50

How do you style an input type=\"file\" button?

30条回答
  •  抹茶落季
    2020-11-21 12:18

    You don't need JavaScript for this! Here is a cross-browser solution:

    See this example! - It works in Chrome/FF/IE - (IE10/9/8/7)

    The best approach would be to have a custom label element with a for attribute attached to a hidden file input element. (The label's for attribute must match the file element's id in order for this to work).

    
    
    

    As an alternative, you could also just wrap the file input element with a label directly: (example)

    
    

    In terms of styling, just hide1 the input element using the attribute selector.

    input[type="file"] {
        display: none;
    }
    

    Then all you need to do is style the custom label element. (example).

    .custom-file-upload {
        border: 1px solid #ccc;
        display: inline-block;
        padding: 6px 12px;
        cursor: pointer;
    }
    

    1 - It's worth noting that if you hide the element using display: none, it won't work in IE8 and below. Also be aware of the fact that jQuery validate doesn't validate hidden fields by default. If either of those things are an issue for you, here are two different methods to hide the input (1, 2) that work in these circumstances.

提交回复
热议问题