Is it posible for an input field to have one font-family
and it’s placeholder another?
I have tried to change font-family
for the input’s placeholder with an already defined @font-face
in CSS but it’s not working:
CSS
.mainLoginInput::-webkit-input-placeholder {
font-family: 'myFont', Arial, Helvetica, sans-serif;
}
.mainLoginInput:-moz-placeholder {
font-family: 'myFont', Arial, Helvetica, sans-serif;
}
HTML
<input class="mainLoginInput" type="text" placeholder="Username" />
How can I solve this problem?
Radllaufer
1671 gold badge2 silver badges9 bronze badges
asked Jan 25, 2013 at 14:55
In case someone want the placeholders selectors for all browsers :
.mainLoginInput::-webkit-input-placeholder {
font-family: 'myFont', Arial, Helvetica, sans-serif;
}
.mainLoginInput:-ms-input-placeholder {
font-family: 'myFont', Arial, Helvetica, sans-serif;
}
.mainLoginInput:-moz-placeholder {
font-family: 'myFont', Arial, Helvetica, sans-serif;
}
.mainLoginInput::-moz-placeholder {
font-family: 'myFont', Arial, Helvetica, sans-serif;
}
answered May 6, 2014 at 10:12
PreviewPreview
34.9k10 gold badges91 silver badges112 bronze badges
2
Use this for major browser support :
HTML:
<input type="text" placeholder="placeholder text.." class="mainLoginInput" />
CSS:
.mainLoginInput::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
font-family: 'myFont', Arial, Helvetica, sans-serif;
opacity: 1; /* Firefox */
}
.mainLoginInput:-ms-input-placeholder { /* Internet Explorer 10-11 */
font-family: 'myFont', Arial, Helvetica, sans-serif;
}
.mainLoginInput::-ms-input-placeholder { /* Microsoft Edge */
font-family: 'myFont', Arial, Helvetica, sans-serif;
}
Details reference link
answered Dec 14, 2018 at 9:01
ArifArif
5,7924 gold badges49 silver badges78 bronze badges
Found it…
Prefix for Firefox 19+ users is ::-moz-placeholder
And the code looks like this
.mainLoginInput::-moz-placeholder {
font-family: 'myFont', Arial, Helvetica, sans-serif;
}
answered Jan 25, 2013 at 15:13
GoldieGoldie
1,5605 gold badges21 silver badges33 bronze badges
1
Simply like this
.mainLoginInput::placeholder{
font-family: -Your font here-;
}
answered Jun 13, 2018 at 6:50
Here is the complete use of ::placeholder
pseudo-element:
::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: pink;
}
::-moz-placeholder { /* Firefox 19+ */
color: pink;
}
:-ms-input-placeholder { /* IE 10+ */
color: pink;
}
:-moz-placeholder { /* Firefox 18- */
color: pink;
}
All placeholders in Firefox have an opacity value applied to them, so in order to fix this we need to reset that value:
::-moz-placeholder {
opacity: 1;
}
Source
answered Jan 2, 2017 at 15:30
Giacomo PaitaGiacomo Paita
1,4012 gold badges12 silver badges21 bronze badges
В HTML5 есть замечательный атрибут — placeholder (текст-подсказка для элементов ввода). Задается он следующим образом:
<input type=«text» placeholder=«type here some text» />
Обычно этот текст отображается серым цветом, но допустим у нас есть необходимость стилизовать этот текст с помощью CSS.
Пока это можно сделать только в Google Chrome, Safari и Firefox, так как в Opera пока еще нет возможность задавать для него стили, а IE не поддерживает его вовсе.
CSS правила для webkit и mozilla:
input::-webkit-input-placeholder {}
input:-moz-placeholder {}
Только имейте ввиду, что нельзя совмещать эти селекторы в один, и если вы напишете:
input:-moz-placeholder,
input::-webkit-input-placeholder { }
то CSS правила не будут работать. И обратите внимание, что для webkit надо писать два двоеточия, а для mozilla — одно.
Еще несколько примеров:
/* стили для webkit */
#field2::-webkit-input-placeholder { color:#00f; }
#field3::-webkit-input-placeholder {
color:#090;
background:lightgreen;
text-transform:uppercase;
}
#field4::-webkit-input-placeholder {
font-style:italic;
text-decoration:overline;
letter-spacing:3px; color:#999;
}/* стили для mozilla */
#field2:-moz-placeholder { color:#00f; }
#field3:-moz-placeholder {
color:#090; background:lightgreen;
text-transform:uppercase;
}
#field4:-moz-placeholder {
font-style:italic;
text-decoration:overline;
letter-spacing:3px;
color:#999;
}
Также следует заметить, что разные браузеры по разному поддерживают стили для плейсхолдера. Например в Firefox вы можете задать для него цвет фона, а в Chrome нет.
Список поддерживаемых CSS стилей для атрибута placeholder:
Chrome 10(Win 7) | Chrome 11 (Win 7) | Firefox 4(Win 7) | Safari 3.1(Win XP & OS X) | Safari 5(Win 7 & OS X) | Opera 11(Win 7) | |
background-color | нет | нет | + | нет | + | нет |
border | нет | нет | + | нет | + | нет |
color | + | + | + | нет | + | нет |
font-size | + | + | + | нет | + | нет |
font-style | + | + | + | нет | + | нет |
font-weight | + | + | + | нет | + | нет |
letter-spacing | + | + | + | нет | + | нет |
line-height | нет | нет | нет | нет | нет | нет |
padding top/bottom | нет | нет | + | нет | + | нет |
padding left/right | нет | нет | + | нет | нет | нет |
text-decoration | нет | нет | + | нет | + | нет |
text-transform | нет | нет | + | нет | + | нет |
The ::placeholder
CSS pseudo-element represents the placeholder text in an <input>
or <textarea>
element.
Try it
Only the subset of CSS properties that apply to the ::first-line
pseudo-element can be used in a rule using ::placeholder
in its selector.
Note: In most browsers, the appearance of placeholder text is a translucent or light gray color by default.
Syntax
Accessibility concerns
Color contrast
Contrast Ratio
Placeholder text typically has a lighter color treatment to indicate that it is a suggestion for what kind of input will be valid, and is not actual input of any kind.
It is important to ensure that the contrast ratio between the color of the placeholder text and the background of the input is high enough that people experiencing low vision conditions will be able to read it while also making sure there is enough of a difference between the placeholder text and input text color that users do not mistake the placeholder for inputted data.
Color contrast ratio is determined by comparing the luminosity of the placeholder text and the input background color values. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. Large text is defined as 18.66px and bold or larger, or 24px or larger.
- WebAIM: Color Contrast Checker
- MDN Understanding WCAG, Guideline 1.4 explanations
- Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0
Usability
Placeholder text with sufficient color contrast may be interpreted as entered input. Placeholder text will also disappear when a person enters content into an <input>
element. Both of these circumstances can interfere with successful form completion, especially for people with cognitive concerns.
An alternate approach to providing placeholder information is to include it outside of the input in close visual proximity, then use aria-describedby
to programmatically associate the <input>
with its hint.
With this implementation, the hint content is available even if information is entered into the input field, and the input appears free of preexisting input when the page is loaded. Most screen reading technology will use aria-describedby
to read the hint after the input’s label text is announced, and the person using the screen reader can mute it if they find the extra information unnecessary.
<label for="user-email">Your email address</label>
<span id="user-email-hint" class="input-hint">Example: jane@sample.com</span>
<input
id="user-email"
aria-describedby="user-email-hint"
name="email"
type="email" />
- Placeholders in Form Fields Are Harmful — Nielsen Norman Group
Windows High Contrast Mode
Placeholder text will appear with the same styling as user-entered text content when rendered in Windows High Contrast Mode. This will make it difficult for some people to determine which content has been entered, and which content is placeholder text.
- Greg Whitworth — How to use -ms-high-contrast
Labels
Placeholders are not a replacement for the <label>
element. Without a label that has been programmatically associated with an input using a combination of the for
and id
attributes, assistive technology such as screen readers cannot parse <input>
elements.
- MDN Basic form hints
- Placeholders in Form Fields Are Harmful — Nielsen Norman Group
Examples
Change placeholder appearance
This example shows some of the adjustments that you can make to the styles of placeholder text.
HTML
<input placeholder="Type here" />
CSS
input::placeholder {
color: red;
font-size: 1.2em;
font-style: italic;
}
Result
Opaque text
Some browsers (such as Firefox) set the default opacity
of placeholders to something less than 100%. If you want fully opaque placeholder text, set opacity
to 1
.
HTML
<input placeholder="Default opacity" />
<input placeholder="Full opacity" class="force-opaque" />
CSS
::placeholder {
color: green;
}
.force-opaque::placeholder {
opacity: 1;
}
Result
Specifications
Specification |
---|
CSS Pseudo-Elements Module Level 4 # placeholder-pseudo |
Browser compatibility
BCD tables only load in the browser
See also
- The
:placeholder-shown
pseudo-class styles an element that has an active placeholder. - Related HTML elements:
<input>
,<textarea>
- HTML forms
Используйте псевдоэлемент ::placeholder
для стилизации дефолтного текста в элементе input
или textarea
. Большинство современных браузеров поддерживают это, но для старых браузеров требуются префиксы.
::placeholder { color: deeppink; font-size: 5rem; text-transform: uppercase; }
HTML
Префиксы
Используемый мной синтаксис поддерживается большинством современных браузеров:
::placeholder { color: deeppink; }
Но для более старых браузеров вам нужно будет использовать префиксы поставщика.
/* WebKit, Edge */ ::-webkit-input-placeholder { color: deeppink; } /* Firefox 4-18 */ :-moz-placeholder { color: deeppink; opacity: 1; } /* Firefox 19+ */ ::-moz-placeholder { color: deeppink; opacity: 1; } /* IE 10-11 */ :-ms-input-placeholder { color: deeppink; } /* Edge */ ::-ms-input-placeholder { color: deeppink; } /* MODERN BROWSER */ ::placeholder { color: deeppink; }
Вау! Я знаю, это огромный список. И вы можете заметить довольно много разных вариантов реализации. Итак, давайте разберем эти различия и поймем, что здесь происходит.
Псевдоэлемент против псевдокласса
Вы можете заметить, что я использую двойное двоеточие ::
. Это называется псевдоэлементом и было введено в CSS3. Если бы мы использовали одно двоеточие :
, это назвали бы псевдоклассом.
Поскольку псевдоэлемент, ::
был представлен в CSS3, а не в более ранних версиях CSS, некоторые старые браузеры, такие как Internet Explorer, просто никогда не поддерживали его. Принимая во внимание, что псевдокласс, :
был представлен ранее (в CSS1 и CSS2). Вот почему гораздо больше браузеров, включая Internet Explorer, поддерживают его.
Следовательно, в нашем ::placeholder
префиксе поставщика вы будете использовать смесь псевдокласса и псевдоэлемента.
Непрозрачность Placeholder в Firefox по умолчанию
Хорошо, с чем это связано opacity: 1
для Firefox. Это потому, что по умолчанию для placeholder Firefox применяется значение непрозрачности. Таким образом, чтобы переопределить это, мы должны установить его принудительно. Таким образом, наш placeholder будет отображаться и не будет иметь блеклого внешнего вида по умолчанию.
CSS-обработка неверных селекторов
Таким образом, вы также можете подумать, почему мы не просто сгруппировали все префиксы вендоров вместе как в примере ниже:
::-moz-placeholder, /* Firefox 19+ */ :-moz-placeholder /* Firefox 4-18 */ { color: deeppink; opacity: 1; }
Ну, это потому, что в CSS3 было правило, которое гласит:
группа селекторов, содержащая недопустимый селектор, недействительна.
Давайте посмотрим на пример, чтобы увидеть, что это значит. Вот правильный CSS-селектор
h1 { color: blue; }
Так что в нашем HTML это будет выглядеть как ожидалось
Hello
Но что произойдет, если мы добавим неверный селектор CSS
h1, /* valid */ h2::poop /* invalid */ { color: blue; }
Так как в группе есть недопустимый селектор CSS. Вся группа будет считаться недействительной, и стилизация не будет применена.
Hello
Вот почему нам нужны отдельные правила для каждого браузера. В противном случае вся группа будет игнорироваться всеми браузерами.
⭐️ НО! похоже, это можно изменить в CSS4.
Как правило, если в цепочке или группе селекторов присутствует недопустимый псевдоэлемент или псевдокласс, весь список селекторов является недействительным. Если псевдоэлемент (но не псевдокласс) имеет префикс -webkit-, то по состоянию на Firefox 63 браузеры Blink, Webkit и Gecko предполагают, что он действителен, не аннулирует список выбора.
Подробнее об этом читайте в статье Криса Койера «Один неверный псевдо-селектор равен целому игнорируемому селектору»
Поддерживаемые стили
Вот список всех стилей, которые вы можете применить к вашему placeholder:
background
свойстваcolor
font
свойстваletter-spacing
line-height
opacity
text-decoration
text-indent
text-transform
vertical-align
word-spacing
Проблемы доступности
Способность стилизовать заполнители — это круто. Но мне нужно отметить кое-что действительно важное — текст-заполнитель не заменяет элемент метки !! Я был виновен в этом, когда впервые попал в веб-программирование 🙁. Когда ваша форма основана исключительно на инструкциях-заполнителях без меток, это очень вредно для доступности. Доступность важна не только для того, чтобы сделать ваш веб-сайт доступным для всех, но и для повышения удобства работы пользователей. И, в конечном итоге, создание лучшего сайта или веб-приложения.
Вот действительно потрясающая статья о том, как использовать заполнители без каких-либо меток. Ниже приведены три основных тезиса:
- Поскольку placeholder исчезает в при вводе, он может напрягать кратковременную память вашего пользователя
- Без label пользователи не могут проверить свою работу перед отправкой формы.
- Когда появляются сообщения об ошибках, люди не знают, как решить проблему.
Автоматически добавлять Vendor-префиксы
Если вы не хотите иметь дело со всеми префиксами вендоров, вы можете использовать PostCSS с плагином Autoprefixer . Этот плагин будет анализировать ваш CSS и добавлять префиксы.
If you’re wondering how to change placeholder text in CSS, then you’re on the right page. HTML inputs have an attribute called placeholder
that allows you to include temporary placeholder text that disappears when the user starts typing in the field. For example:
Code language: HTML, XML (xml)
<input type="text" placeholder="Enter Your Name">
Browsers apply specific styles to the placeholder text by default, which is usually a shade of grey for the font color. You can change the styles of the placeholder in all modern browsers using the ::placeholder
pseudo-element:
Code language: CSS (css)
::placeholder { font-style: italic; font-size: 1em; color: mintcream; background: thistle; padding: 5px; }
Notice you’re able to style just about anything, including the background. These aren’t necessarily recommended styles, but they demonstrate what’s possible.
Current browser support for ::placeholder
is strong in modern browsers, but if you want deeper support, you’ll have to include different lines in your CSS to account for older syntax. So if you had multiple styles, as shown above, your code would look like this:
::-webkit-input-placeholder { font-style: italic; font-size: 1em; color: mintcream; background: thistle; padding: 5px; } :-moz-placeholder { font-style: italic; font-size: 1em; color: mintcream; background: thistle; padding: 5px; } ::-moz-placeholder { font-style: italic; font-size: 1em; color: mintcream; background: thistle; padding: 5px; } :-ms-input-placeholder { font-style: italic; font-size: 1em; color: mintcream; background: thistle; padding: 5px; } ::input-placeholder { font-style: italic; font-size: 1em; color: mintcream; background: thistle; padding: 5px; } ::placeholder { font-style: italic; font-size: 1em; color: mintcream; background: thistle; padding: 5px; }
Code language: CSS (css)
Not very efficient! Ideally, you would want all the selectors on a single line, in order to save all that code, but that won’t work due to the way browsers parse selectors. When a browser finds a selector it doesn’t support, the entire selector is ignored.
If you’re using a CSS preprocessor like Sass, you can save some keystrokes by using a function to generate all the blocks, like this:
Code language: PHP (php)
$placeholder: ('::-webkit-input-placeholder', ':-moz-placeholder', '::-moz-placeholder', ':-ms-input-placeholder', '::input-placeholder', '::placeholder'); @each $selector in $placeholder { #{$selector} { font-style: italic; font-size: 1em; color: mintcream; background: thistle; padding: 5px; } }
Here is a demo that uses the Sass function to enable these placeholder styles in a cross-browser fashion:
As a final note, if you find styles aren’t applying in certain older browsers, you can try using the !important keyword.