Дизайн input file css

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

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

Стандартный вид

.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
$('.input-file input[type=file]').on('change', function()< let file = this.files[0]; $(this).closest('.input-file').find('.input-file-text').html(file.name); >);

Результат:

Обычная кнопка

.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
$('.input-file input[type=file]').on('change', function()< let file = this.files[0]; $(this).next().html(file.name); >);

Результат:

В виде input text

.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
$('.input-file input[type=file]').on('change', function()< let file = this.files[0]; $(this).closest('.input-file').find('.input-file-text').html(file.name); >);

Результат:

Input file со списком выбранных файлов

.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
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 = '
' + ''; $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; >

Результат:

Загрузка изображений с превью

.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
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 = '
' + '' + ''; $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; >

Источник

Читайте также:  If image null php

Стилизация Input File

Стилизация Input File

Данный скрипт позволяет менять внешний вид Input File (появится зеленая галочка) после того, как файл будет загружен.

(function() { 'use strict'; $('.input-file').each(function() { var $input = $(this), $label = $input.next('.js-labelFile'), labelVal = $label.html(); $input.on('change', function(element) { var fileName = ''; if (element.target.value) fileName = element.target.value.split('\\').pop(); fileName ? $label.addClass('has-file').find('.js-fileName').html(fileName) : $label.removeClass('has-file').html(labelVal); }); }); })();

Пример 3: Брутальный Input File

HTML разметка

CSS стилизация

@import "https://fonts.googleapis.com/css?family=Varela+Round"; .example-3{box-sizing:border-box} .example-3{position:relative;font:1em/1.6 "Varela Round",Arial,sans-serif;color:#999;font-weight:400;max-width:25em;padding:1em;} .example-3 h2{font-weight:400} .example-3 .filupp > input[type="file"]{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0} .example-3 .filupp{position:relative;background:#242424;display:block;padding:1em;font-size:1em;width:100%;height:3.5em;color:#fff;cursor:pointer;box-shadow:0 1px 3px #0b0b0b} .example-3 .filupp:before{content:"";position:absolute;top:1.5em;right:.75em;width:2em;height:1.25em;border:3px solid #dd4040;border-top:0;text-align:center} .example-3 .filupp:after{content:"\f178";font-family: FontAwesome;-webkit-transform:rotate(-90deg);-moz-transform:rotate(-90deg);-ms-transform:rotate(-90deg);-o-transform:rotate(-90deg);transform:rotate(-90deg);position:absolute;top:.65em;right:.45em;font-size:2em;color:#dd4040;line-height:0} .example-3 .filupp-file-name{width:75%;display:inline-block;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;word-wrap:normal}

JS скрипт

$(document).ready(function() { $('input[type="file"]').change(function(){ var value = $("input[type='file']").val(); $('.js-value').text(value); }); });

Поделиться с друзьями

Похожие статьи:

Комментарии ( )

Отличная стилизация Input! Давно искал вариант со скрепкой.
Но при попытке передать файл на сервер, у меня появилась ошибка «Не удалось открыть поток: отказано в доступе». Что я сделал?
Я загуглил эту тему и вот что нашел. Может кому то пригодиться.
1. Узнайте код ошибки php. Поместите этот код в начало файла php.
ini_set(‘error_reporting’, E_ALL);ini_set(‘display_errors’, 1);ini_set(‘display_startup_errors’, 1);
2. К папке должен быть доступ 777. Проверь это.
3. Тег должен иметь атрибут enctype = «multipart/form-data» method = «post».
4. Полностью открой и посмотри массив $ _FILES на сервере.
print_r ($_FILES);
5. Открой и посмотри массив $ _FILES на клиенте.
file = document.getElementById(«get_avatar»).files[0];parts = file.name.split(‘.’);
var a = file.size;var b = parts.pop();var c = file.type;alert(a+b+c);
6. Проверь права пользователя и группы пользователей на каталог.
cd /var/www/your_site/user
ls -l
Подробнее: http://profi.spage.me/php/check-file-input-on-php-and-jquery-why-error

Вы должны авторизоваться, чтобы оставлять комментарии.

Программирование

Продвижение сайтов

Полезные инструменты

Источник

Styling file inputs like a boss

Default file inputs in firefox and chrome

HTML elements have default styles applied to them by individual browsers. These styles could vary depending on the browser, and applying your own custom styles could range from being very easy to unnecessarily complicated (sometimes impossible). In this article we would be going through how to style file inputs, which happens to be one of those difficult elements to style using CSS. If you’ve worked with file inputs in your application, you’d know that the default style doesn’t look so nice. Here’s an example of how it looks in chrome and firefox in case you’re wondering. The good news is, we can fix this. the bad news is we won’t be able to use the «conventional» method.

Styling File Inputs

 class="file-input">  type="file" id="file" class="file">  for="file">Select file  

Hiding the input

.file  opacity: 0; width: 0.1px; height: 0.1px; position: absolute; > 

You might be thinking, why not use display: none to hide the input. Well the problem with that is the input field would be removed from the layout and then become inaccessible to people using screen readers which would be very bad. Another important thing to note is the label . With file inputs, clicking on the label also opens up the file picker, so we can use that to our advantage and style the label anyway we want.

Styling the label

Now that we’ve hidden the default input, we can decide to style the label however we want. For simplicity sake, let’s just make it look like a button.

.file-input label  display: block; position: relative; width: 200px; height: 50px; border-radius: 25px; background: linear-gradient(40deg, #ff6ec4, #7873f5); box-shadow: 0 4px 7px rgba(0, 0, 0, 0.4); display: flex; align-items: center; justify-content: center; color: #fff; font-weight: bold; cursor: pointer; transition: transform .2s ease-out; > 

Styled input with purple gradient

Accessibility

So we’ve been able to style the label to look like a button, but that’s not all. We need to add some sort of indications to the label for when people hover on the field, or try to focus on the file field using the keyboard. I’m just going to do something simple here and increase the size of the label when that happens.

input:hover + label, input:focus + label  transform: scale(1.02); > 
input:focus + label  outline: 1px solid #000; outline: -webkit-focus-ring-color auto 2px; > 

The -webkit-focus-ring-color is used to get the default outline look on webkit browsers like chrome or safari. For non webkit browsers, a black outline would be applied to the element.

Javascript Enhancements

We can use JavaScript to display the name and size of the file selected. This would create a slightly more natural feel to the custom field. So let’s modify our HTML and CSS a bit.

 class="file-input">  type="file" id="file" class="file">  for="file"> Select file  class="file-name">

.file-name  position: absolute; bottom: -35px; left: 10px; font-size: 0.85rem; color: #555; > 

Finally, we would add an event listener to the file input and reflect the name and size of the file below the label.

const file = document.querySelector('#file'); file.addEventListener('change', (e) =>  // Get the selected file const [file] = e.target.files; // Get the file name and size const  name: fileName, size > = file; // Convert size in bytes to kilo bytes const fileSize = (size / 1000).toFixed(2); // Set the text content const fileNameAndSize = `$fileName> - $fileSize>KB`; document.querySelector('.file-name').textContent = fileNameAndSize; >); 

Here’s how everything looks.
And that’s it for the file input. You could decide to style this however you want to get the behavior you want, it’s up to you. Happy styling!😁😁

Источник

Произвольный вид поля file в html-форме, одинаковый во всех браузерах

Не смотря на развитие, внедрение новых стандартов и плюшек в браузерах, у нет единых стандартов, как отображать элемент/> по умолчанию. Более того, у этого элемента нет атрибутов, позволяющих его в какой-то мере стилизовать.
Из-за необходимости привести это поле формы к единому виду во всех браузерах и «вписать» в разработанный дизайн, после поисков и анализа материалов в интернете был разработан метод замены вида поля формы на html+css, и js для расширения функциональности.

Как по умолчанию выглядит это поле?

image

Так он выглядит в Internet Explorer 9:

image

А так — в Firefox:

image

В Google Chrome:

image

В Opera:

image

В Safari:

Стилизация поля file
.fileform < background-color: #FFFFFF; border: 1px solid #CCCCCC; border-radius: 2px; cursor: pointer; height: 26px; overflow: hidden; padding: 2px; position: relative; text-align: left; vertical-align: middle; width: 230px; >.fileform .selectbutton < background-color: #A2A3A3; border: 1px solid #939494; border-radius: 2px; color: #FFFFFF; float: right; font-size: 16px; height: 20px; line-height: 20px; overflow: hidden; padding: 2px 6px; text-align: center; vertical-align: middle; width: 50px; >.fileform #upload

image

Теперь во всех браузерах поле формы выглядит одинаково, при этом форма выбора файла всё так же появляется по клику и на поле и на кнопку:

Главный недостаток полученного решения от стандартной формы — оно никак визуально не сигнализирует о том, что файл был выбран. Эта проблема решается с использованием javascript.

Добавление подписи о выбранном файле

Добавим к полю функцию-обработчик событий, а к блоку — еще один блок-заголовок и, конечно, его стиль:

Сама функция-обработчик получает полное имя выбранного файла, отбрасывает путь (с проверкойдля разных файловых систем), сохраняет имя с расширением в переменную filename и записывает его в блок fileformlabel.

function getName (str) < if (str.lastIndexOf('\\'))< var i = str.lastIndexOf('\\')+1; >else < var i = str.lastIndexOf('/')+1; >var filename = str.slice(i); var uploaded = document.getElementById("fileformlabel"); uploaded.innerHTML = filename; > 

Теперь поле формы выглядит так (при этом можно менять его размер, цвет, шрифт и выравнивание):

image

Данная заметка — реализация метода, предложенного в статье «Кастомизация input type=”file” с помощью CSS»

Источник

Оцените статью