Как в placeholder вставить иконку

от admin

Create a search icon inside input box with HTML and CSS

Displaying a search icon inside an input box is a nice way to indicate to the user that it is indeed a search input.

Google search input Duckduckgo search inputDuckduckgo search input Twitter search inputTwitter search input CodePen search inputCodePen search input Gmail search inputGmail search input Vimeo search inputVimeo search input

Markup

The HTML for our search box with an icon will consist of a form , input , and button elements.

The form will act as a wrapper, as well as will react to the submit event.

The input element should have a type attribute equal to the search value. It will ensure a better usability on mobile devices. The keyboard with a layout suited for search will be shown.

NOTE: To improve UX you can also specify an input placeholder e.g. “Search…”. This will give a user an additional hint that this is indeed a search input.

Finally, the button type attribute should have a submit value. The proper button type will ensure the form can be submitted via button click without additional events for this button. The button will also act as an icon.

Styling

First, we’ll need to set the form element display property value to flex . This will allow us to properly align input and button elements.

We’ll also set a border property to wrap elements closer together.

Next, we need to set styles for our search input box. It should span the full width of the container element, as well as have some visually appealing properties.

Finally, let’s add some styling to the submit button. We will hide the text of the button with text-indent and overflow properties, and display in its place a magnifying glass icon.

To display the icon we can use encoded svg as a background image.

The last touch is to set the :focus state on input and button elements:

No button example

If you’re willing to show an icon inside an input without it being a button, just remove the submit button from the form.

You can leave existing form and input styles but in this case, set the icon as a background for the input.

HTML5 image icon to input placeholder

I’d like to add an image icon to an input placeholder, like in this picture: enter image description here

Please note that this is a placeholder, so when the user starts typing, the icon also disappears.

I came with the following solution for webkit (Safari+Chrome) using ::-webkit-input-placeholder and ::before . Unfortunately, the straightforward application to mozilla seems not to work.

So my question is: is there a cross-browser solution to add an image icon to an input placeholder?

Solution for webkit:

5 Answers 5

  1. You can set it as background-image and use text-indent or a padding to shift the text to the right.
  2. You can break it up into two elements.

Honestly, I would avoid usage of HTML5/CSS3 without a good fallback. There are just too many people using old browsers that don’t support all the new fancy stuff. It will take a while before we can drop the fallback, unfortunately 🙁

The first method I mentioned is the safest and easiest. Both ways requires Javascript to hide the icon.

CSS:

HTML:

Javascript:

September 25h, 2013

I can’t believe I said "Both ways requires JavaScript to hide the icon.", because this is not entirely true.

The most common timing to hide placeholder text is on change, as suggested in this answer. For icons however it’s okay to hide them on focus which can be done in CSS with the active pseudo-class.

Heck, using CSS3 you can make it fade away!

November 5th, 2013

Of course, there’s the CSS3 ::before pseudo-elements too. Beware of browser support though!

Используйте значок шрифта Awesome в заполнителе

можно ли использовать значок Font Awesome в заполнителе? Я читал, где HTML не допускается в заполнителе. Есть ли обходной путь?

11 ответов:

вы не можете добавить значок и текст, потому что вы не можете применить другой шрифт к части заполнителя, однако, если вы удовлетворены только значок, то он может работать. Значки FontAwesome-это просто символы с пользовательским шрифтом (вы можете посмотреть на FontAwesome.css для экранированного символа Юникода в content правило. В меньшем исходном коде он находится в переменные.меньше задача будет заключаться в том, чтобы поменять шрифты, когда вход не пуст. Совместите его с в jQuery, как этой.

С этим CSS:

и этот (простой) jQuery

переход между шрифтами не будет гладким, однако.

Если вы используете FontAwesome 4.7 этого должно быть достаточно:

список шестнадцатеричных кодов можно найти в шрифт Awesome cheatsheet. Однако в последнем FontAwesome 5.0 этот метод не работает (даже если вы используете подход CSS в сочетании с обновленным font-family ).

Я решил с помощью этого метода:

в CSS я использовал этот код fontAwesome class:

в HTML я добавил fontawesome class и fontawesome icon code внутри местозаполнителя:

Вы можете ознакомиться в CodePen.

где поддерживается, вы можете использовать ::input-placeholder pseudoselector в сочетании с ::before .

Смотрите пример по адресу:

http://codepen.io/JonFabritius/pen/nHeJg

Я просто работал над этим и наткнулся на эту статью, из которой я изменил этот материал:

HTML5 Placeholder Styling with CSS

Я использую Ember (версия 1.7.1), и мне нужно было как привязать значение ввода, так и иметь заполнитель, который был значком FontAwesome. Единственный способ привязать значение в Ember (что я знаю) — это использовать встроенный помощник. Но это приводит к тому, что заполнитель экранируется,»  » просто появляется точно так же, текст.

если вы используете Ember или нет, вам нужно установить CSS заполнителя ввода, чтобы иметь семейство шрифтов FontAwesome. Это SCSS (с помощью Бурбон для стиля заполнителя):

если вы просто используете руль, как уже упоминалось ранее, вы можете просто установить HTML-объект в качестве заполнителя:

если вы используете Ember привязать заполнитель к свойству контроллера, который имеет значение unicode.

в шаблоне:

на контроллере:

и стоимость обязательных работ ладно!

placeholder example

Я делаю это путем добавления fa-placeholder класс для ввода текста:

<input type=»text» name=»search» placeholder=»&#xF002;» />

Итак, в css просто добавьте это:

.fa-placholder

это хорошо работает для меня.

обновление:

чтобы изменить шрифт во время ввода текста пользователем, просто добавьте свой шрифт после шрифта awesome

.fa-placholder

использовать placeholder=»&#xF002;» в ваш вклад. Вы можете найти Юникод в FontAwesome page http://fontawesome.io/icons/ . Но вы должны убедиться, что добавить style=»font-family: FontAwesome;» в ваш вклад.

кто-нибудь интересуется a Шрифт Удивительный 5 реализация:

Не указывайте общее семейство шрифтов» Font Awesome 5″, вам нужно специально закончить ветку значков, с которыми вы работаете. Вот я использую филиал «бренды», например.

более подробно используйте значок шрифта Awesome (5) в тексте заполнителя ввода

есть некоторая небольшая задержка и джанк, как изменения шрифта в ответе, предоставленном Джейсоном. Использование события » change «вместо» keyup » решает эту проблему.

игнорируя jQuery это можно сделать с помощью ::placeholder входного элемента.

часть css

ЛУЧШАЯ ЧАСТЬ: Вы можете иметь различное семейство шрифтов для заполнителя и текста

я добавил текст и значок вместе в местозаполнитель.

CSS:

How To Use Font Awesome Icon In Placeholder

The Placeholder attribute specifies a short hint that describes the expected value of an input field or text area. Before the user enters a value, the short hint is displayed in the field.

Читать:
Model rn 10b что это

Font Awesome is a toolkit for icons and fonts, based on CSS and LESS.

In this article, we will learn how to use Font Awesome icon in placeholder.

Add the following CSS to use the Font Awesome icons:

NOTE: To use Font Awesome 5 icons sign up for an account at Font Awesome, and get a code. Once you get the code you can start using Font Awesome, by including only one line to your webpage.

Here, in the example, we are using Font Awesome 4.

You can place Font Awesome icons by using the prefix &#x and the icon’s Unicode.

NOTE: With Font Awesome 4 you must have to apply style=”font-family: FontAwesome;” and With Font Awesome 5 you must have to apply style=”font-family: ‘Font Awesome 5 Brands’;”.

Now, the question is how we can find the icon’s Unicode?

Follow the steps given below to get the icon’s Unicode.

Firstly, go to the Font Awesome’s icon list then click the icon you want to use.

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