Search code examples
htmlcssformspseudo-class

How to change the color of the file input button in a form after a file is selected with css?


I am making a simple webpage with a form that has inputs with type file in it, and I want to change the border color of the "select file" button when I select a file to indicate that a file is selected.

I have tried using the :focus pseudo-class in css to try and change the color when pressed, but this only works until something else on the page is clicked. I also tried the :visited pseudo-class, but nothing happened.

Here is the relevant html code:

<input type="file" id="file-input"></input>
<label for="file-input" class="file-button">Select File</label>

css:

.file-button {
    display: block;
    margin: 10px auto;
    width: 400px;
    border-radius: 10px;
    text-align: center;
    justify-content: center;
    color: black;
    font-weight: bold;
    font-size: 36pt;
    border: 5px solid grey;
    padding:8px 0px;

}

input[type="file"]{
    opacity: 0;
    width: 0.1px;
    height: 0.1px;
    overflow: hidden;
    z-index: -1;
    position: absolute;

}

input[type="file"]:focus+label {
    border-color: black;  
}

Solution

  • There are a couple of ways to do this. If you have the complete js code then it would be much easier to answer. Basically you could use a ternary to determine if the file is uploaded (stored in state), then change the css based on such.

    For instance:

    const [isUploaded, setIsUploaded] = useState(null)
    
    //Change the upload to true once a file is selected
    
    <label for="file-input" class={isUploaded ? "file-button-after-upload" : "file-button-before-upload">Select File</label>