Стилизация input file

Примеры изменения вида стандартного поля для загрузки файлов (input[type=file]) с помощью CSS и JS.

1
<form method="post" enctype="multipart/form-data">
	<label class="input-file">
	   	<input type="file" name="file">
 	   	<span class="input-file-btn">Выберите файл</span>           
	   	<span class="input-file-text">Максимум 10мб</span>
 	</label>
</form>
HTML
.input-file {
	position: relative;
	display: inline-block;
}
.input-file-btn {
	position: relative;
	display: inline-block;
	cursor: pointer;
	outline: none;
	text-decoration: none;
	font-size: 14px;
	vertical-align: middle;
	color: rgb(255 255 255);
	text-align: center;
	border-radius: 4px;
	background-color: #419152;
	line-height: 22px;
	height: 40px;
	padding: 10px 20px;
	box-sizing: border-box;
	border: none;
	margin: 0;
	transition: background-color 0.2s;
}
.input-file-text {
	padding: 0 10px;
	line-height: 40px;
	display: inline-block;
}
.input-file input[type=file] {
	position: absolute;
	z-index: -1;
	opacity: 0;
	display: block;
	width: 0;
	height: 0;
}

/* Focus */
.input-file input[type=file]:focus + .input-file-btn {
	box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}

/* Hover/active */
.input-file:hover .input-file-btn {
	background-color: #59be6e;
}
.input-file:active .input-file-btn {
	background-color: #2E703A;
}

/* Disabled */
.input-file input[type=file]:disabled + .input-file-btn {
	background-color: #eee;
}
CSS
$('.input-file input[type=file]').on('change', function(){
	let file = this.files[0];
	$(this).closest('.input-file').find('.input-file-text').html(file.name);
});
JS

Результат:

2
<form method="post" enctype="multipart/form-data">
	<label class="input-file">
	   	<input type="file" name="file">		
	   	<span>Выберите файл</span>
 	</label>
</form>
HTML
.input-file {
	position: relative;
	display: inline-block;
}
.input-file span {
	position: relative;
	display: inline-block;
	cursor: pointer;
	outline: none;
	text-decoration: none;
	font-size: 14px;
	vertical-align: middle;
	color: rgb(255 255 255);
	text-align: center;
	border-radius: 4px;
	background-color: #419152;
	line-height: 22px;
	height: 40px;
	padding: 10px 20px;
	box-sizing: border-box;
	border: none;
	margin: 0;
	transition: background-color 0.2s;
}
.input-file input[type=file] {
	position: absolute;
	z-index: -1;
	opacity: 0;
	display: block;
	width: 0;
	height: 0;
}

/* Focus */
.input-file input[type=file]:focus + span {
	box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}

/* Hover/active */
.input-file:hover span {
	background-color: #59be6e;
}
.input-file:active span {
	background-color: #2E703A;
}

/* Disabled */
.input-file input[type=file]:disabled + span {
	background-color: #eee;
}
CSS
$('.input-file input[type=file]').on('change', function(){
	let file = this.files[0];
	$(this).next().html(file.name);
});
JS

Результат:

3
<form method="post" enctype="multipart/form-data">
	<label class="input-file">
	   	<span class="input-file-text" type="text"></span>
	   	<input type="file" name="file">        
 	   	<span class="input-file-btn">Выберите файл</span>
 	</label>
</form>
HTML
.input-file {
	position: relative;
	display: inline-block;
}
.input-file-text {
	padding: 0 10px;
	line-height: 40px;
	text-align: left;
	height: 40px;
	display: block;
	float: left;
	box-sizing: border-box;
	width: 200px;
	border-radius: 6px 0px 0 6px;
	border: 1px solid #ddd;
}
.input-file-btn {
position: relative;
	display: inline-block;
	cursor: pointer;
	outline: none;
	text-decoration: none;
	font-size: 14px;
	vertical-align: middle;
	color: rgb(255 255 255);
	text-align: center;
	border-radius: 0 4px 4px 0;
	background-color: #419152;
	line-height: 22px;
	height: 40px;
	padding: 10px 20px;
	box-sizing: border-box;
	border: none;
	margin: 0;
	transition: background-color 0.2s;
}
.input-file input[type=file] {
	position: absolute;
	z-index: -1;
	opacity: 0;
	display: block;
	width: 0;
	height: 0;
}

/* Focus */
.input-file input[type=file]:focus + .input-file-btn {
	box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}

/* Hover/active */
.input-file:hover .input-file-btn {
	background-color: #59be6e;
}
.input-file:active .input-file-btn {
	background-color: #2E703A;
}

/* Disabled */
.input-file input[type=file]:disabled + .input-file-btn {
	background-color: #eee;
}
CSS
$('.input-file input[type=file]').on('change', function(){
	let file = this.files[0];
	$(this).closest('.input-file').find('.input-file-text').html(file.name);
});
JS

Результат:

4
<form method="post" enctype="multipart/form-data">
	<div class="input-file-row">
		<label class="input-file">
		   	<input type="file" name="file[]" multiple>		
		   	<span>Выберите файл</span>
 		</label>
		<div class="input-file-list"></div>  
	</div>  
</form>
HTML
.input-file-row {
	display: inline-block;
}
.input-file {
	position: relative;
	display: inline-block;
}
.input-file span {
	position: relative;
	display: inline-block;
	cursor: pointer;
	outline: none;
	text-decoration: none;
	font-size: 14px;
	vertical-align: middle;
	color: rgb(255 255 255);
	text-align: center;
	border-radius: 4px;
	background-color: #419152;
	line-height: 22px;
	height: 40px;
	padding: 10px 20px;
	box-sizing: border-box;
	border: none;
	margin: 0;
	transition: background-color 0.2s;
}
.input-file input[type=file] {
	position: absolute;
	z-index: -1;
	opacity: 0;
	display: block;
	width: 0;
	height: 0;
}

/* Focus */
.input-file input[type=file]:focus + span {
	box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}

/* Hover/Active */
.input-file:hover span {
	background-color: #59be6e;
}
.input-file:active span {
	background-color: #2E703A;
}

/* Disabled */
.input-file input[type=file]:disabled + span {
	background-color: #eee;
}

/* Список файлов */
.input-file-list {
	padding: 10px 0;
}
.input-file-list-item {
	margin-bottom: 10px;
}
.input-file-list-remove {
	color: red;
	text-decoration: none;
	display: inline-block;
	margin-left: 5px;
}
CSS
var dt = new DataTransfer();

$('.input-file input[type=file]').on('change', function(){
	let $files_list = $(this).closest('.input-file').next();
	$files_list.empty();

	for(var i = 0; i < this.files.length; i++){
		let new_file_input = '<div class="input-file-list-item">' +
			'<span class="input-file-list-name">' + this.files.item(i).name + '</span>' +
			'<a href="#" onclick="removeFilesItem(this); return false;" class="input-file-list-remove">x</a>' +
			'</div>';
		$files_list.append(new_file_input);
		dt.items.add(this.files.item(i));
	};
	this.files = dt.files;
});

function removeFilesItem(target){
	let name = $(target).prev().text();
	let input = $(target).closest('.input-file-row').find('input[type=file]');	
	$(target).closest('.input-file-list-item').remove();	
	for(let i = 0; i < dt.items.length; i++){
		if(name === dt.items[i].getAsFile().name){
			dt.items.remove(i);
		}
	}
	input[0].files = dt.files;  
}
JS
5
<form method="post" enctype="multipart/form-data">
	<div class="input-file-row">
		<label class="input-file">
		   	<input type="file" name="file[]" multiple accept="image/*">		
		   	<span>Выберите файл</span>
 		</label>
		<div class="input-file-list"></div>  
	</div>
</form>
HTML
.input-file-row {
	display: inline-block;
}
.input-file {
	position: relative;
	display: inline-block;
}
.input-file span {
	position: relative;
	display: inline-block;
	cursor: pointer;
	outline: none;
	text-decoration: none;
	font-size: 14px;
	vertical-align: middle;
	color: rgb(255 255 255);
	text-align: center;
	border-radius: 4px;
	background-color: #419152;
	line-height: 22px;
	height: 40px;
	padding: 10px 20px;
	box-sizing: border-box;
	border: none;
	margin: 0;
	transition: background-color 0.2s;
}
.input-file input[type=file] {
	position: absolute;
	z-index: -1;
	opacity: 0;
	display: block;
	width: 0;
	height: 0;
}

/* Focus */
.input-file input[type=file]:focus + span {
	box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}

/* Hover/active */
.input-file:hover span {
	background-color: #59be6e;
}
.input-file:active span {
	background-color: #2E703A;
}

/* Disabled */
.input-file input[type=file]:disabled + span {
	background-color: #eee;
}

/* Список c превью */
.input-file-list {
	padding: 10px 0;
}
.input-file-list-item {
	display: inline-block;
	margin: 0 15px 15px;
	width: 150px;
	vertical-align: top;
	position: relative;
}
.input-file-list-item img {
	width: 150px;
}
.input-file-list-name {
	text-align: center;
	display: block;
	font-size: 12px;
	text-overflow: ellipsis;
	overflow: hidden;
}
.input-file-list-remove {
	color: #fff;
	text-decoration: none;
	display: inline-block;
	position: absolute;
	padding: 0;
	margin: 0;
	top: 5px;
	right: 5px;
	background: #ff0202;
	width: 16px;
	height: 16px;
	text-align: center;
	line-height: 16px;
	border-radius: 50%;
}
CSS
var dt = new DataTransfer();

$('.input-file input[type=file]').on('change', function(){
	let $files_list = $(this).closest('.input-file').next();
	$files_list.empty();
 
	for(var i = 0; i < this.files.length; i++){
		let file = this.files.item(i);
		dt.items.add(file);    
   
		let reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onloadend = function(){
			let new_file_input = '<div class="input-file-list-item">' +
				'<img class="input-file-list-img" src="' + reader.result + '">' +
				'<span class="input-file-list-name">' + file.name + '</span>' +
				'<a href="#" onclick="removeFilesItem(this); return false;" class="input-file-list-remove">x</a>' +
			'</div>';
			$files_list.append(new_file_input); 
		}
	};
	this.files = dt.files;
});

function removeFilesItem(target){
	let name = $(target).prev().text();
	let input = $(target).closest('.input-file-row').find('input[type=file]');	
	$(target).closest('.input-file-list-item').remove();	
	for(let i = 0; i < dt.items.length; i++){
		if(name === dt.items[i].getAsFile().name){
			dt.items.remove(i);
		}
	}
	input[0].files = dt.files;  
}
JS

Результат:

20.07.2022, обновлено 10.03.2024
46711
Предыдущая запись Знак рубля в HTML/CSS

Комментарии 4

eeeMan.rg Rori eeeMan.rg Rori
30 марта 2023 в 13:26
что за дно делало эти примеры? ни в одном примере нельзя перетащить файл на кнопку. Если хотите чтобы объяснил как сделать чтобы нативный драгэнддроп работал пишите)
Хаскел Инкерман Хаскел Инкерман
4 сентября 2023 в 18:01
Если ты такое дно что ищешь как стилизовать input, то пи*ди поменьше. А если ты такой бог кода, что ты вообще забыл на этом сайте?
Infinity Team Infinity Team
1 июля 2023 в 08:39
Всё хорошо работает. Удалил $files_list.empty(); чтобы не оставалось скрытых загруженных файлов при выборе новых. Это ввело меня в заблуждение. Я даже подумал, что крестики на самом деле не удаляют файлы...
Владимир Лобанов Владимир Лобанов
12 ноября 2023 в 09:37
Здесь сделано ровно пол дела, и если мы захотим отправить изображение на
сервер, то получим пустой результат.
Добавим строку загрузки на сервер с type="submit" и в проге load_file.php получим пустые данные
<form action="load_file.php" enctype="multipart/form-data" method="post">
<input type="file" name="path" multiple accept="image/*">
<input type="submit" value="upload" name="path" >
А ведь наша главная цель загрузить изображение на сервер !?

, чтобы добавить комментарий.

Другие публикации

Загрузка изображений с превью AJAX + PHP + MySQL
В данной статье представлена упрощенная реализация загрузки изображений с превью через AJAX с сохранением в базу данных...
30820
+22
Стилизация Radio Button
Несколько примеров изменения вида радио кнопок на чистом CSS. Единственное неудобство метода в том, что приходится указывать уникальные id.
176753
+32
Работа с Input File JS/jQuery
Сборник приёмов jQuery для работы с полями загрузки файлов через интерфейс File.
9280
-1
Contenteditable – текстовый редактор
Если добавить атрибут contenteditable к элементу, его содержимое становится доступно для редактирования пользователю, а...
43139
+34
Генерация счета на оплату PDF PHP
С помощью расширения dompdf можно легко сформировать PDF файл. По сути, dompdf - это конвертер HTML в PDF который...
65079
+33
Селект с чекбоксами
Селект с множественным выбором (select multiple) весьма не удобен, при выборе часто забываешь нажимать сtrl и все сбрасывается. В место него можно использовать чекбоксы в выпадающем списке.
36056
+10