Css change 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
Читайте также:  Create static map java

А если 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

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

Источник

::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.

Источник

How to Change Placeholder Text in CSS (for HTML Inputs)

Louis Lazaris

  • by Louis Lazaris
  • September 24, 2022

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:

input type="text" placeholder="Enter Your Name">
Code language: HTML, XML (xml)

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:

::placeholder < font-style: italic; font-size: 1em; color: mintcream; background: thistle; padding: 5px; >
Code language: CSS (css)

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:

$placeholder: ('::-webkit-input-placeholder', ':-moz-placeholder', '::-moz-placeholder', ':-ms-input-placeholder', '::input-placeholder', '::placeholder'); @each $selector in $placeholder < # font-style: italic; font-size: 1em; color: mintcream; background: thistle; padding: 5px; > >
Code language: PHP (php)

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.

Note: To the best of our knowledge, the information above and the snippet are accurate and up to date. However, in case you notice something wrong, please report snippet or leave a comment below.

Louis Lazaris is a writer, speaker, author, and front-end web developer who’s been involved in the web development industry in various forms since 2000. He blogs about code on his primary website and curates a series of newsletters for tech professionals and software developers.

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!

  • 50+ Best Free WordPress Themes
  • How to Make a WordPress Website: Ultimate Guide
  • Best WordPress Hosting
  • Best Cheap WordPress Hosting
  • Managed WordPress Hosting Guide
  • Top 5 eCommerce Hosting Solutions
  • Best Web Hosting for Small Business
  • Best eCommerce Platforms
  • Best Email Marketing Tools
  • Best SMTP Providers Compared
  • Best Live Chat Software Solutions
  • How to Build Your Own Website

Источник

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.

Источник

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