Rails 4: how to apply custom CSS to Rails form file field

Thibaud Clement picture Thibaud Clement · Oct 9, 2015 · Viewed 8k times · Source

I have a Rails 4 app, that uses Rails' default form (I am NOT using Simple Form).

One of my forms allows users to upload an image (thanks to Paperclip):

<td>
  <%= f.file_field :image, value: "Choose a file" %>
</td>

I would like to style the "choose a file button" with custom CSS.

I tried to apply an id to my td, as follows:

<td id="upload_image">
  <%= f.file_field :image, value: "Choose a file" %>
</td>

and then I tried to style it with the following CSS code:

#upload_image input {
    background-color: #2c3e50;
    background-image: none;
    border: none;
    color: #FFF;
    padding: 5px 10px 5px 10px;
}

But this resulted in styling the td itself:

enter image description here

And I still get this ugly button with the default style.

—————

UPDATE: if styling the button itself is not possible, I would like to at least put the "no file chosen" label ("aucun fichier choisi" in French) under the button, since at the moment it is taking a lot of horizontal room on my page).

Is that even possible?

—————

How can I make this work?

Answer

ThorstenC picture ThorstenC · Mar 9, 2018

This is my solution: just wrap a form field in a label and hide it. No javascript.

<label class="btn btn-default btn-change-avatar">
    Upload new image
    <span style="display:none;">
      <%= form.file_field :avatar, id: "fileUploader"%>
    </span>
  </label>