testproftest 23
testproftest 23

Reputation: 35

How can I apply a Font Awesome icon to a custom file input?

I want to make a file input with HTML and CSS; I use the class of custom-file-input as shown in the picture, but instead of "browse" I want to add an icon which is fas fa-paperclip and add the label file before the input

.custom-file-input~.custom-file-label::after {
  content: "fas fa-paperclip";
}
<div class="custom-file">
  <p> file : </p>
  <input type="file" class="custom-file-input" id="validatedCustomFile" required>
  <label class="custom-file-label" for="validatedCustomFile"></label>
</div>

what is wrong why the icon is not shown ?

enter image description here

Upvotes: 1

Views: 1018

Answers (1)

isherwood
isherwood

Reputation: 61063

You can't dump classes in as content and expect that to work. You also can't apply classes to pseudo-elements in general.

Instead, you can add the Font Awesome 5 icon as an absolutely-positioned element.

.custom-file {
  position: relative;
  background: #ddd;
}

.custom-file i {
  position: absolute;
  right: 10px;
  bottom: 2px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

<div class="custom-file">
  <p> file : </p>
  <input type="file" class="custom-file-input" id="validatedCustomFile" required>
  <label class="custom-file-label" for="validatedCustomFile"></label>
  <i class="fas fa-paperclip"></i>
</div>

If you wanted a nice CSS-only solution, consider downgrading to Font Awesome 4 so you can use HTML entities as content:

.custom-file-input:after {
  content: "\f0c6"; /* inspect an icon for this value */
  font-family: FontAwesome; /* intentionally no fallback */
  font-size: 16px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha512-5A8nwdMOWrSz20fDsjczgUidUBR8liPYU+WymTZP1lmY9G6Oc7HlZv156XqnsgNUzTyMefFTcsFH/tnJE/+xBg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div class="custom-file">
  <p> file : </p>
  <input type="file" class="custom-file-input" id="validatedCustomFile" required>
  <label class="custom-file-label" for="validatedCustomFile"></label>
</div>

Upvotes: 2

Related Questions