How to style input file

How to style input file

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

Сегодня будем стилизовать input type file. Т.к. стилизация тесно связана с обработкой input file на фронтенде, мы так же рассмотрим, как обработать выбранный файл и отправить на сервер. Скрипт будет работать для множества форм с возможностью не только загрузить файл при клике на кнопку, но так же перетаскиванием файла (drag-and-drop) в область загрузки. Если вам не нужен тот или иной функционал, вы легко сможете удалить часть кода.

1. Стилизация input type file

Сначала нам необходимо создать html-разметку.

Скроем input и стилизуем кнопку для загрузки файла.

2. Drag-and-drop загрузка файлов

Структура останется прежней, т.к. наша первоначальная разметка вполне подойдёт для создания drag-and-drop области.

Теперь напишем JavaScript для обработки событий перетаскивания файлов на веб-страницу. А уже в следующем пункте рассмотрим, как использовать кнопку добавления файла и область Drag-and-drop одновременно.

3. Совместное использование кнопки «Прикрепить файл» и Drag-and-drop

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

HTML-структура и CSS останутся без изменений. Объеденим JavaScript код.

4. Отправка множества input file multiple

Ранее мы успешно отправили все даннные формы (текстовые поля и файлы) на сервер.

Рассмотрим пример отправки multiple формы с множеством input file на почту.

Style input type file? [duplicate]

Is it possible to style a input element of type file without worrying about browser compatibility? In my case I need to implement a background image and round border(1px), the button should also be customised if possible.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

6 Answers 6

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Follow these steps then you can create custom styles for your file upload form:

1.) This is the simple HTML form(please read the HTML comments I have written here bellow)

2.) Then use this simple script to pass the click event to file input tag.

Now you can use any type of a styling without worrying how to change default styles. I know this very well, because I have been trying to change the default styles for month and a half. believe me it’s very hard because different browsers have different upload input tag. So use this one to build your custom file upload forms.Here is the full AUTOMATED UPLOAD code.

Same solution via Jquery. Works if you have more than one file input in the page.

After looking around on Google for a long time, trying out several solutions, both CSS, JavaScript and JQuery, i found that most of them were using an Image as the button. Some of them were hard to use, but i did manage to piece together something that ended out working out for me.

The important parts for me was:

This is the solution i came up with. And hope it can be of use to others as well.

To test this solution, make a new html file and paste the content into it.

Как стилизовать поле для отправки файла

Привет, друзья. Давно просят сделать статью о том, как стилизовать input с type file, то есть поле для прикрепления файла. Однажды, косвенно я затрагивал эту тему в одной из статей, но сегодня мы остановимся на ней подробнее.

Конечно, как обычно есть несколько путей решить эту задачу. Это:

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Конечно, если у вас серьезный проект и вы делаете его с нуля, то позаботитесь об этом заранее и будете знать, как решите эту проблему, когда столкнетесь с ней. Но, иногда, приходится дорабатывать уже существующий сайт и в таком случае нецелесообразно подключать фреймворк для решения одной конкретной задачи. Да и если бы вы использовали фреймворк, то не пришли бы читать эту статью, поэтому сразу откинем этот вариант.

Остается попробовать самостоятельно привести все в порядок или воспользоваться плагином. Давайте остановимся на этих 2 вариантах подробнее, чтобы у вас больше не возникало вопросов как всё-таки стилизовать тег input с атрибутом type=file. Я подробно опишу вариант самостоятельной стилизации, а в конце дам ссылку на плагин, который делает практически тоже самое.

Самостоятельная стилизация тега input с типом «файл»

Существует несколько подходов к решению этой задачи, но, как по мне, самым правильным является способ, когда мы используем label для отслеживания клика, который располагается рядом с полем для прикрепления файла.

Не претендую на авторство кода и разметки, ведь еще в 2016 году я подсмотрел метод реализации на одном зарубежном блоге. Поэтому и ссылка сохранилась, так как я давно планировал написать эту стать, но в свое время откладывал, потом забыл, а совсем недавно получил пару обращений от читателей и решил сесть и написать все-таки. Поэтому, если хотите, читайте оригинал.

Итак, обычно я оборачиваю все инпуты и элементы, которые относятся к ним в общий контейнер. Мне так удобней, легче верстать, позиционировать и стилизовать.

Как я уже и говорил, мы будем отслеживать клик по label, который связан с инпутом, при этом само поле, которое предназначено для отправки файла мы скроем, задав ему прозрачность «0».

Вот так сейчас выглядит поле в браузере:

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Добавим стили, чтобы получить описываемый результат. То есть скроем input, оставим только label, поместим в него иконку и сделаем его похожим на обычную кнопку, но сначала, добавим кое-что в верстку:

Теперь добавим стили:

Вот что получилось:

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Как видите, уже лучше, но пока мы не видим никакой реакции на то, что файл выбран. Нет никакого уведомления и никакой индикации. Давайте исправим это. Под формой, ближе к закрывающему тегу body добавьте следующий скрипт:

Для примера добавил сразу 2 поля, чтобы продемонстрировать что это работает и в случае, если у вас несколько форм или полей.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Как видите, все не очень сложно, плюс, без jQuery, так что если у вас она уже не используется, то можно не тянуть ее за собой, ради такого скромного функционала.

Стилизация «input type file» при помощи плагина

Теперь давайте рассмотрим вариант стилизация поля для отправки файла при помощи jQuery плагина. Называется он jQuery Fileinput. Как я уже говорил, делает он практически тоже самое, просто автоматически.

Для настройки сначала подключаем сам плагин и jQuery:

Затем создаем input:

И инициализируете плагин:

После инициализации сам инпут скроется, а на его месте появится кнопка.

Чтобы задать ей свой класс и поместить в нее свой текст, нужно передать в fileinput html. Например так:

Для наглядности, смотрите пример на jsfiddle, а на сегодня все. Надеюсь, что у вас больше не осталось вопросов по поводу того, как стилизовать input с type fifle.

Похожие публикации

13 комментариев

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Годнота, спасибо, я просто делал всегда рамку вокруг инпута и центрировал его. Вообще есть много споров по поводу того, стоит ли индивидуализировать этот и другие элементы, или оставить так, как многие уже привыкли, то есть по умолчанию и одинаково +- во всех браузерах.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Что делает multifile-upload-field-for-contact-form-7? Если просто добавляет enctype=’multipart/form-data’, то попробуйте добавить этот параметр скриптом обычным, а не плагином.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Отличная стилизация Input. Давно искал такой вариант дизайна. Но при попытке передать файл на сервер, у меня появилась ошибка «Не удалось открыть поток: отказано в доступе». Что я сделал?
Я загуглил эту тему и вот что нашел. Может кому то пригодиться.
1. Узнайте код ошибки php. Поместите этот код в начало файла php.

2. К папке должен быть доступ 777. Проверь это.
3. Тег form должен иметь атрибут enctype = «multipart/form-data» method = «post».

6. Проверь права пользователя и группы пользователей на каталог.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Aleksey, спасибо, что не оставили без внимания и дали такой развернутый ответ. Кому-то обязательно пригодится!

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Доброго времени суток. Оформил по данному примеру кнопку отправки.
Прошу прощения за, может быть, тупой вопрос, но.
Как получить вложенные файлы на почту? Если с остальными полями понятно
[tel* tel-136] выведет телефон который введет пользователь и т.д.
Но что в данном случае вставить в поле «Прикрепленные файлы», чтобы файл пришел на почту?
Еще раз прошу прощения, за может быть примитивный вопрос.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Добрый день sn_eg, несколько я понял, вы хотите отправить email с вложением. При помощи input file мы получаем файл от пользователя и загружаем его к себе на сервер в папку. Выше есть код. А что бы отправить email с этим файлом из этой папки с сервера, надо делать php код отправки email с вложенным файлом. Вот здесь есть пример: http://www.php.su/articles/?cat=examples&page=060
Если вы делаете отправку email с сервера первый раз. То разберите сперва пример попроще. PHP отправка email с сервера (загуглите пример). А затем если получится, email с вложением.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Я впервые сталкиваюсь вообще с отправкой файлов с формы. Все сделал по инструкции с поста, но так и не понял в какой папке хранятся файлы отправленные с формы cf7. На самом деле, проблема была только в стилизации кнопки отправки файлов, но более разумного решение, чем тут, не нашел. И стилизовал так как нужно, но столкнулся с рядом вопросов, с которыми ранее не сталкивался. В какую папку сохраняются файлы? Где их можно найти? Тыкните носом, пожалуйста.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

1.Узнаем имя файла.
2.Берем сам файл.
3.Путь (папка) на сервере куда будет скопирован файл.
4.Перемещаем файл с браузера на сервер.

Если есть трудности, напишите мне пожалуйста в VK https://vk.com/alekseyvanin
Я чем смогу, помогу!

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Спасибо большое. Как доберусь до ноута, посмотрю/попробую.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Здравствуйте. подскажите на счет ошибки. у меня скрипт добавлен к форме с валидацией. сначала отработало, потом стало ошибку выдавать Uncaught TypeError: Cannot read properties of null (reading ‘innerText’) и ругается на forEach.
в сайт после добавление вносились правки. но совсем мелкие. типа на jquery парочка классов была навешана. и хз чего перестало отрабатывать. вроде все осталось как было

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Здравствуйте, сложно ответить как решить эту проблему, мало данных. Надо смотреть на сайте, в консоле отладки кода. Желательно ещё иметь доступ к папке сайта, что бы править код. Если хотите, скажу своему помощнику он отладит код.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Styling file inputs like a boss

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.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

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

Let’s create a simple file input in our HTML.

Exit fullscreen mode

To style a file input, the first thing we would need to do is get rid of the default file input.

Hiding the input

Exit fullscreen mode

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.

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.

Exit fullscreen mode

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

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.

Exit fullscreen mode

We can also decide to add an outline to the label on focus

Exit fullscreen mode

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.

Exit fullscreen mode

Exit fullscreen mode

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

Exit fullscreen mode

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!😁😁

Styling & Customizing File Inputs the Smart Way

A tutorial on how to style and customize in a semantic, accessible way using the element and some JavaScript.

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

There are quite a few techniques for “customizing” the element. I tried most of them, but none was good enough to have on Readerrr (for importing feeds by uploading a file). Probably the worst technique was the one where the input element is put into a container (which imitates a button), and the input follows the cursor so that when you click anywhere on the container, you actually click the input. Sounds interesting and weird at the same time, right? Anyway, it had some unacceptable drawbacks (usability, touch).

So, pressing any of these two elements gives us the same result. That means that the most difficult part is… solved! No JavaScript, no other complex solutions like cursor position tracking, just these two lines. See for yourself:

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Now let’s just style it and make this look like a normal button.

Hiding the

First off, we need to hide the ugly duckling. CSS properties such as display: none or visibility: hidden will not work out. The reasons are: the input value will not be sent to the server on form submit; the input will be excluded out of tab order (you want your website to be accessible, right?). I set up a combination of CSS properties/values for hiding the input visually but keeping it visible for the browser:

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Styling the

Since the element is visually the button, you can use all of your creative CSS juices on it. I’m sticking to something very simple for now:

Accessibility

How do you know that an element on the website is pressable? Firstly, the element should communicate a feeling that you can tap or click on it. Secondly, the cursor icon should change to an appropriate one when hovering the element. The former we’ve solved previously, let’s solve the latter, because labels do not trigger a cursor change by default:

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input fileHow to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Keyboard Navigation

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Possible Touch Issues

JavaScript Enhancement

Probably and hopefully the last thing missing is indicating if files were selected. The file input does usually indicate that, but in our case the input is visually hidden. Luckily, there is a way out: a tiny JavaScript enhancement. The text of a label becomes the name of the selected file. If there were multiple files selected, the text will tell us how many of them were selected.

There is also a jQuery version of this code presented in the source of the demo files. Make sure to check them out.

A little explanation:

This is how the final result looks like:

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

What if JavaScript is not available?

The CSS part accordingly:

How to style input file. Смотреть фото How to style input file. Смотреть картинку How to style input file. Картинка про How to style input file. Фото How to style input file

Firefox Bug

It is quite unexpected that Firefox completely ignores the input[type=»file»]:focus expression, whereas :hover and :active work just fine! Surprisingly, Firefox allows to catch the focus event in JavaScript, so the workaround is adding a class to the file input element that let’s us control the focus style:

Check out the example styles in the demo to see how to style the file input element according to your needs. Make sure to take a look at the source code of the demo and feel free to use this technique in your projects. Happy uploading!

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *