Css style input placeholder text

Стилизуем placeholder при помощи CSS. Синтаксис, трюки, поддерживаемые стили в html5

Атрибут placeholder применяется для призыва к действию внутри пустых элементов input и textarea. В этой статье мы рассмотрим возможности стилизации текста placeholder-a, а также некоторые трюки, которые позволят сделать его более удобным и функциональным.

Итак, начнем с примера для тех, кто не знает, что такое placeholder.

html

Стиль placeholder-a можно изменить с помощью такого набора css правил:

css

::-webkit-input-placeholder ::-moz-placeholder /* Firefox 19+ */ :-moz-placeholder /* Firefox 18- */ :-ms-input-placeholder

Выглядит страшновато, не правда ли? Дело в том, что этого до сих пор нет в стандартах. Каждый браузер по-своему реализовал поддержку стилизации placeholder-а.

В IE и старых firefox (до 18-го) placeholder считается псевдоклассом, а в новых firefox, webkit и blink – псевдоэлементом.

Нужно сказать, что поддерживаются не все возможные css свойства. Большинство современных браузеров позволяют изменить:

  • font (и сопутствующие свойства)
  • background (и сопутствующие свойства)
  • color
  • word-spacing
  • letter-spacing
  • text-decoration
  • vertical-align
  • text-transform
  • line-height
  • text-indent
  • text-overflow
  • opacity

А если placeholder не вмещается?

Иногда поля для ввода текста сокращаются по ширине из-за особенностей лейаута, в частности на мобильных девайсах. В этом случае длинный текст placeholder-а будет некрасиво обрезан. Чтобы предотвратить это, вы можете использовать text-overflow: ellipsis . Такой синтаксис будет работать во всех новых браузерах.

css

input[placeholder] input::-moz-placeholder input:-moz-placeholder input:-ms-input-placeholder

Как скрыть placeholder при фокусе?

Скрывание placeholder-а происходит по-разному.

  1. в некоторых браузерах при получении фокуса инпутом
  2. в других браузерах при наличии хотя бы одного введенного символа

Мне больше нравится первый вариант. Для того, чтобы задать такое поведение во всех браузерах, поддерживающих placeholder, определим следующие css правила:

css

:focus::-webkit-input-placeholder :focus::-moz-placeholder :focus:-moz-placeholder :focus:-ms-input-placeholder

Скрываем placeholder красиво

Можно также добавить transition для появления и скрытия placeholder-a:

css

/* плавное изменение прозрачности placeholder-а при фокусе */ .input1::-webkit-input-placeholder .input1::-moz-placeholder .input1:-moz-placeholder .input1:-ms-input-placeholder .input1:focus::-webkit-input-placeholder .input1:focus::-moz-placeholder .input1:focus:-moz-placeholder .input1:focus:-ms-input-placeholder /* сдвиг placeholder-а вправо при фокусе*/ .input2::-webkit-input-placeholder .input2::-moz-placeholder .input2:-moz-placeholder .input2:-ms-input-placeholder .input2:focus::-webkit-input-placeholder .input2:focus::-moz-placeholder .input2:focus:-moz-placeholder .input2:focus:-ms-input-placeholder /* сдвиг placeholder-а вниз при фокусе*/ .input3::-webkit-input-placeholder .input3::-moz-placeholder .input3:-moz-placeholder .input3:-ms-input-placeholder .input3:focus::-webkit-input-placeholder .input3:focus::-moz-placeholder .input3:focus:-moz-placeholder .input3:focus:-ms-input-placeholder

Надеюсь, вам это пригодится. Пишите замечания и предложения в комментариях.

Читайте также:  Python time now in utc

Источник

: : placeholder

Псевдоэлемент : : placeholder используется для стилизации текста-подсказки (плейсхолдера) в полях ввода и .

Пример

Скопировать ссылку «Пример» Скопировано

  input class="form-input" type="email" placeholder="Например: mygre@ema.il">      
 .form-input::placeholder  color: gray;> .form-input::placeholder  color: gray; >      

Как понять

Скопировать ссылку "Как понять" Скопировано

Как пишется

Скопировать ссылку "Как пишется" Скопировано

Два двоеточия и ключевое слово placeholder .

Стиль применится ко всем подсказкам на странице:

 ::placeholder  color: gray;> ::placeholder  color: gray; >      

Стиль применится только к подсказкам у полей ввода с классом email - input :

 .email-input::placeholder  color: darkblue;> .email-input::placeholder  color: darkblue; >      

Подсказки

Скопировать ссылку "Подсказки" Скопировано

💡 Для стилизации подсказки можно использовать только следующие свойства:

  • все шрифтовые свойства, начинающиеся с font (например, font - size или font - style );
  • все свойства для работы с фоном, начинающиеся с background - (например, background - color или background - size );
  • свойство color ;
  • свойства word - spacing , letter - spacing , text - decoration , text - transform и line - height ;
  • свойства text - shadow , группу свойств text - decoration и vertical - align .

На практике

Скопировать ссылку "На практике" Скопировано

Денис Ежков советует

Скопировать ссылку "Денис Ежков советует" Скопировано

🛠 Желательно стилизовать подсказку таким образом, чтобы визуально она отличалась от введённого текста. Как правило, её делают полупрозрачной, либо просто светлее вводимого текста.

Источник

::placeholder

The ::placeholder CSS pseudo-element represents the placeholder text in an or 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.

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 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 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 addresslabel> span id="user-email-hint" class="input-hint">Example: jane@sample.comspan> input id="user-email" aria-describedby="user-email-hint" name="email" type="email" /> 

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.

Labels

Placeholders are not a replacement for the 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 elements.

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

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: ,
  • HTML forms

Found a content problem with this page?

This page was last modified on Apr 12, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Стилизация HTML5 плейсхолдера с помощью CSS

В HTML5 есть замечательный атрибут — placeholder (текст-подсказка для элементов ввода). Задается он следующим образом:

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

Пока это можно сделать только в Google Chrome, Safari и Firefox, так как в Opera пока еще нет возможность задавать для него стили, а IE не поддерживает его вовсе.

CSS правила для webkit и mozilla:

то 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 нет нет + нет + нет

Источник

How TO - Change Placeholder Color

Learn how to change the color of the placeholder attribute with CSS.

Placeholder Color

Step 1) Add HTML:

Use an input element and add the placeholder attribute:

Example

Step 2) Add CSS:

In most browsers, the placeholder text is grey. To change this, style the placeholder with the non-standard ::placeholder selector. Note that Firefox adds a lower opacity to the placeholder, so we use opacity: 1 to fix this.

Example

Tip: Read more about the ::placeholder selector in our CSS Reference: CSS ::placeholder Property.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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