Hi folks 👋, It is always a pain to style form-controls such as file-field, checkbox etc.
While working on a project, I came across the same situation when I had to style a file field and Google helped me to find a number of tricks people had been using to accomplish it, but I was looking for a native way to do it.
After spending some minutes , the magic happened and I found a pseudo element while reading mdn docs. In this article, I will show you how it is possible to achieve.
First of all, the magical pseudo element is ::file-selector-button
, So let's start using it.
Step 1 : Create a file field inside <form></form>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Field Styling</title>
<!----- link your stylesheet ------>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<form class="form">
<input type="file" class="file--field">
</form>
</body>
</html>
Step 2 : apply some basic styling and center the form
html,
body {
height:100%;
}
*, *::after, *::before {
margin:0;
padding:0;
box-sizing:border-box;
}
body {
font:400 1em/1.6 'Poppins',sans-serif;
display:flex;
justify-content:center;
align-items:center;
}
.form {
width:70%;
max-width:540px;
margin:0 auto;
}
Step 3 : now style file field
.file--field,
.file--field::file-selector-button {
font:500 1em/1.6 'Poppins',sans-serif;
}
.file--field {
width:100%;
border:1px solid hsl(220, 13%, 68%);
border-radius:.4em;
}
.file--field::file-selector-button {
--color-1:hsl(270deg, 90%, 50%);
--color-2:hsl(250deg, 100%, 60%);
padding:.75em 1em;
border:none;
background-image:linear-gradient(to top right, var(--color-1), var(--color-2));
color:#fff;
margin-right:1em;
text-transform:uppercase;
letter-spacing:.5px;
transition:background-color 200ms linear;
}
.file--field::file-selector-button:hover,
.file--field::file-selector-button:focus {
--color-1:rgb(115, 9, 221);
--color-2:rgb(45, 14, 201);
cursor:pointer;
}
Here is your result
Conclusion
You no longer need those hacks to style ::file-selector-button
. You can checkout its browser support on caniuse.
If the article taught you something then don't forget to follow me. You can also connect with me on Twitter.
Keep Pushing your limit🙂