Styling an input type=“file” button

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

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

30条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 11:53

    Working example here with native Drag and drop support : https://jsfiddle.net/j40xvkb3/

    When styling a file input, you shouldn't break any of native interaction the input provides.

    The display: none approach breaks the native drag and drop support.

    To not break anything, you should use the opacity: 0 approach for the input, and position it using relative / absolute pattern in a wrapper.

    Using this technique, you can easily style a click / drop zone for the user, and add custom class in javascript on dragenter event to update styles and give user a feedback to let him see that he can drop a file.

    HTML :

    
    

    CSS :

    input[type="file"] {
      position: absolute;
      left: 0;
      opacity: 0;
      top: 0;
      bottom: 0;
      width: 100%;
    }
    
    div {
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #ccc;
      border: 3px dotted #bebebe;
      border-radius: 10px;
    }
    
    label {
      display: inline-block;
      position: relative;
      height: 100px;
      width: 400px;
    }
    

    Here is a working example (with additional JS to handle dragover event and dropped files).

    https://jsfiddle.net/j40xvkb3/

    Hope this helped !

提交回复
热议问题