How to color change placeholder

How to color change placeholder

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.

We just launched
W3Schools videos

COLOR PICKER

How to color change placeholder. Смотреть фото How to color change placeholder. Смотреть картинку How to color change placeholder. Картинка про How to color change placeholder. Фото How to color change placeholder

Get certified
by completing
a course today!

CODE GAME

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
Web Courses

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.

::placeholder

The ::placeholder CSS pseudo-element represents the placeholder text in an or

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.

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.

Result

Opaque text

Css placeholder color или как изменить цвет placeholder css

How to color change placeholder. Смотреть фото How to color change placeholder. Смотреть картинку How to color change placeholder. Картинка про How to color change placeholder. Фото How to color change placeholder

Доброго времени, коллеги! Бывало ли у вас такое, что заказчик говорит что плохо виден текст в полях для заполнения формы? Более того, кто ведет свои блоги, знает, что цвет текста в input в комментариях всегда какой-то нечитаемый, блеклый, а браузер Mozilla и вовсе его «размазывает».

Css placeholder color

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

HTML: стандартная конструкция

Префиксы

Для всех современных браузеров достаточно использовать такую конструкцию.

Но если делаете проект на заказ, то рекомендую добавить еще несколько строк. Важно: не объединяйте эти стили вместе с вашими, уже существующими, а прописывайте так как они есть в примере ниже.

Зачем столько кода, спросите вы! Много не мало! А если кроме шуток, то на данный момент этого еще нет в стандартах, и поэтому, в каждом браузере поддержка стилизации placeholder реализована по-своему.

Читайте также:

Трюк: изменение прозрачности

Вообще, существует несколько фишек по стилизации и «анимации» placeholder’а, но если есть необходимость чтобы проект прошел проверку на валидность, то не стоит такими фишками баловаться.

Плагин

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

Документация и демо

Пример на Codepen

На сегодня сеанс окончен, до встречи в следующей статье! Не делайте гуано-сайтов, не надо!

Стилизация 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 нет.

Change input placeholder * color only

I have multiple input fields some fields are required and required field mention with * so I need to change input placeholder * color only, not change whole placeholder color check below image what I exactly need.

How to color change placeholder. Смотреть фото How to color change placeholder. Смотреть картинку How to color change placeholder. Картинка про How to color change placeholder. Фото How to color change placeholder
I have tried below code to achieve this but it can change whole color of placeholder

How to color change placeholder. Смотреть фото How to color change placeholder. Смотреть картинку How to color change placeholder. Картинка про How to color change placeholder. Фото How to color change placeholder

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

How to color change placeholder. Смотреть фото How to color change placeholder. Смотреть картинку How to color change placeholder. Картинка про How to color change placeholder. Фото How to color change placeholder

How to color change placeholder. Смотреть фото How to color change placeholder. Смотреть картинку How to color change placeholder. Картинка про How to color change placeholder. Фото How to color change placeholder

How to color change placeholder. Смотреть фото How to color change placeholder. Смотреть картинку How to color change placeholder. Картинка про How to color change placeholder. Фото How to color change placeholder

See This:

How to color change placeholder. Смотреть фото How to color change placeholder. Смотреть картинку How to color change placeholder. Картинка про How to color change placeholder. Фото How to color change placeholder

maybe you can use span in the placeholder so you can change the color of *

With the current markup I don’t think this is possible with just CSS, but:

Codepen demo

The trick here is to use the pseudo class:

:placeholder-shown (caniuse)

Input elements can sometimes show placeholder text as a hint to the user on what to type in. See, for example, the placeholder attribute in [HTML5]. The :placeholder-shown pseudo-class matches an input element that is showing such placeholder text.

The idea here is for the text «Password *» to simulate placeholder text.

This is the key selector:

For this reason we still need to set a non-empty placeholder attribute on the input (a simple whitespace is sufficient)

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

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

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