How to Style the Input File Type in Forms using CSS?
Last Updated :
17 Apr, 2024
Customizing the style of file input elements in web forms is essential to enhance the visual appeal of a website. Employing techniques such as CSS styling and the ::file-selector-button to achieve a visually appealing file upload experience. These methods allow for the customization of various design elements, such as padding, border, and font.
In this approach, This ::file-selector-button offers limited styling capabilities but works across most browsers. It targets the button that opens the file selection dialog. This code uses the ‘::file-selector-button’ pseudo-element to style the file input button in forms, giving it a green background, white text, padding, rounded corners, and a pointer cursor.
Note: Limited properties can be applied (background, color, padding, etc.). Doesn’t allow styling text within the button.
Example 1: In the below example styling the input file type in forms using the ::file-selector-button pseudo-element.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Styled File Input (1st Approach)</title>
<style>
input[type="file"]::file-selector-button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<form>
<label for="fileInput">
Upload a File:
</label>
<input type="file" id="fileInput">
</form>
</body>
</html>
Output:
Example 2: In the below example Styling the input file type in forms using CSS, links the file input and custom button to event listeners, triggering a simulated click on the hidden file input when the custom button is clicked.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Styled File Upload</title>
<style>
.custom-file-upload {
position: relative;
display: inline-block;
}
.custom-file-upload button {
padding: 10px 20px;
border: 1px solid #ccc;
border-radius: 5px;
cursor: pointer;
overflow: hidden;
text-align: left;
transition: background-color 0.2s ease-in-out;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
font-family: 'Roboto', sans-serif;
}
.custom-file-upload button:hover {
background-color: #388e3c;
}
.custom-file-upload button::before {
content: "\f0e4";
font-family: FontAwesome;
margin-right: 5px;
}
.custom-file-upload input[type="file"]
::-webkit-file-name-text {
color: black;
}
</style>
</head>
<body>
<div class="custom-file-upload">
<input type="file" id="fileInput"
style="opacity: 0;">
<button>Choose File</button>
</div>
<script>
const fileInput =
document.getElementById('fileInput');
const customButton =
document.querySelector('.custom-file-upload button');
customButton.addEventListener('click', () => {
fileInput.click();
});
</script>
</body>
</html>
Output:
Share your thoughts in the comments
Please Login to comment...