How Can I Hide *Only* the Button (Not Entire Element) for the Input Type File in a Django Form?

896 views Asked by At

I just found this:

How to customize <input type="file">?

But it hides the entire input element. In my case, I'm using Django's form and there is text like "no file selected" or after you choose a file, the file name shows up. I want to keep those bits but customize only the button part of the input element.

See below for current approach.

enter image description here enter image description here

But I want something like the styled one below but that retains the text in the previous images.

enter image description here

Is there a way to do this?

EDIT

I guess I should have been clearer. I saw all the other answers out there but my question is different. First of all, I know how to add attributes to the form class. I'm already doing this. Secondly, the images I attached were from my code. In other words, I already implemented the answers in the so-called duplicates.

My question pertains to the text next to the actual button that says "Browse". I want to style the button but KEEP the text, because this text is dynamic and changes with user action.

As far as I can tell, the other answers (and my assumption) is that the entire element gets styled with the custom CSS, so when it's hidden or obscured, the text is also hidden.

Given this, can anyone propose an answer?

Solution

Thanks to @lmgonzalves, I have realized that my problem was hiding the entire element. I should have just made a button overlay with the custom button like the accepted answer. Thanks again!

2

There are 2 answers

2
lmgonzalves On BEST ANSWER

I have create a demo for you, check:

https://jsfiddle.net/lmgonzalves/uLmLc3xt/5/

The icon is with font-awesome, and here is the code.

HTML:

<label id="upload-file-container" for="photo">
    <input id="photo" type="file" name="photo"/>
    <span class="upload-file-wrapper">
        <i class="fa fa-cloud-upload"></i>
        <span>Click here to upload file</span>
    </span>
</label>

CSS:

#upload-file-container{
    position: relative;
    cursor: pointer;
}

#upload-file-container input{
    position: relative;
    left: 150px; /* Maybe you need to adjust this */
    top: 5px;
}

#upload-file-container .upload-file-wrapper{
    position: absolute;
    left: 0;
    top: -1px;
    background-color: lightgray;
    border: 1px solid gray;
    padding: 5px 0 6px;
    width: 250px;
    text-align: center;
}
1
felipsmartins On

You should set a id or class HTML attribute via Widgets.attrs and customize via CSS, just like this:

Django Form

class MyForm(forms.Form):
    name = forms.FileField(widget=forms.FileInput(attrs={'id': 'upload'}))

CSS

#upload {
 /* ... */
}

Helpful links: