DEV Community

James Hay
James Hay

Posted on

Customising a file input using Tailwind CSS

I recently found out that Tailwind CSS now supports file input customisation as of v3 - (https://tailwindcss.com/blog/tailwindcss-v3#native-form-control-styling)

All the functionality of the file input stays the same but Tailwind allows you to style most things without the usual headache.


Customising a file input's styles

<form>
  <input
    type="file"
    class="block w-full text-sm text-slate-500
        file:mr-4 file:py-2 file:px-4 file:rounded-md
        file:border-0 file:text-sm file:font-semibold
        file:bg-pink-50 file:text-pink-700
        hover:file:bg-pink-100"
  />
</form>
Enter fullscreen mode Exit fullscreen mode

Image description


However, if you do need more customisation you can always build a file input yourself like below.

A custom file input altering the "No file chosen" text using React

const CustomInputExample = () => {
  const [selectedFile, setSelectedFile] = useState("No file chosen");

  return (
    <form>
      <div class="flex flex-row items-center">
        <input
          type="file"
          id="custom-input"
          onChange={(e) => setSelectedFile(e.target.files[0].name)}
          hidden
        />
        <label
          for="custom-input"
          class="block text-sm text-slate-500 mr-4 py-2 px-4
            rounded-md border-0 text-sm font-semibold bg-pink-50
            text-pink-700 hover:bg-pink-100 cursor-pointer"
        >
          Choose file
        </label>
        <label class="text-sm text-slate-500">{selectedFile}</label>
      </div>
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

Image description


A JSFiddle with the examples - (https://jsfiddle.net/DevJamesHay/dh0sz5pe/261/)

Top comments (0)