Атрибут placeholder застосовується для призову до дії всередині порожніх елементів input і textarea. У цій статті ми розглянемо можливості стилізації тексту placeholder-a, а також деякі трюки, які дозволять зробити його більш зручним і функціональним.

Отже, почнемо з прикладу для тих, хто не знає, що таке placeholder.

html

Стиль placeholder-a можна змінити за допомогою такого набору css правил:

css

:: - webkit-input-placeholder (color: # c0392b;) :: - moz-placeholder (color: # c0392b;) / * Firefox 19+ * /: -moz-placeholder (color: # c0392b;) / * Firefox 18- * /: -ms-input-placeholder (color: # c0392b;)

Виглядає страшнувато, чи не так? Справа в тому, що цього досі немає в стандартах. Кожен браузер по-своєму реалізував підтримку стилізації 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 (text-overflow: ellipsis;) input :: - moz-placeholder (text-overflow: ellipsis;) input: -moz-placeholder (text-overflow: ellipsis;) input: -ms-input-placeholder (text-overflow : ellipsis;)

Як приховати placeholder при фокусі?

Переховування placeholder-а відбувається по-різному.

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

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

css

: Focus :: - webkit-input-placeholder (color: transparent): focus :: - moz-placeholder (color: transparent): focus: -moz-placeholder (color: transparent): focus: -ms-input-placeholder ( color: transparent)

Приховуємо placeholder красиво

Можна також додати transition для появи і приховування placeholder-a:

css

/ * Плавне зміна прозорості placeholder-а при фокусі * / .input1 :: - webkit-input-placeholder (opacity: 1; transition: opacity 0.3s ease;) .input1 :: - moz-placeholder (opacity: 1; transition: opacity 0.3s ease;) .input1: -moz-placeholder (opacity: 1; transition: opacity 0.3s ease;) .input1: -ms-input-placeholder (opacity: 1; transition: opacity 0.3s ease;) .input1 : focus :: - webkit-input-placeholder (opacity: 0; transition: opacity 0.3s ease;) .input1: focus :: - moz-placeholder (opacity: 0; transition: opacity 0.3s ease;) .input1: focus : -moz-placeholder (opacity: 0; transition: opacity 0.3s ease;) .input1: focus: -ms-input-placeholder (opacity: 0; transition: opacity 0.3s ease;) / * зрушення placeholder-а вправо при фокусі * / .input2 :: - webkit-input-placeholder (text-indent: 0px; transition: text-indent 0.3s ease;) .input2 :: - moz-placeholder (text-indent: 0px; transition: text-indent 0.3s ease;) .input2: -moz-placeholder (text-indent: 0px; transition: text-indent 0.3s ease;) .input2: -ms-input-placeholde r (text-indent: 0px; transition: text-indent 0.3s ease;) .input2: focus :: - webkit-input-placeholder (text-indent: 500px; transition: text-indent 0.3s ease;) .input2: focus :: - moz-placeholder ( text-indent: 500px; transition: text-indent 0.3s ease;) .input2: focus: -moz-placeholder (text-indent: 500px; transition: text-indent 0.3s ease;) .input2: focus: -ms- input-placeholder (text-indent: 500px; transition: text-indent 0.3s ease;) / * зрушення placeholder-а вниз при фокусі * / .input3 :: - webkit-input-placeholder (line-height: 20px; transition: line-height 0.5s ease;) .input3 :: - moz-placeholder (line-height: 20px; transition: line-height 0.5s ease;) .input3: -moz-placeholder (line-height: 20px; transition: line -height 0.5s ease;) .input3: -ms-input-placeholder (line-height: 20px; transition: line-height 0.5s ease;) .input3: focus :: - webkit-input-placeholder (line-height: 100px; transition: line-height 0.5s ease;) .input3: focus :: - moz-placeholder (line-height: 100px; transition: line-height 0.5s ease;) .input3: focus: -moz-placehold er (line-height: 100px; transition: line-height 0.5s ease;) .input3: focus: -ms-input-placeholder (line-height: 100px; transition: line-height 0.5s ease;)

Сподіваюся, вам це стане в нагоді. Пишіть зауваження і пропозиції в коментарях.

Плейсхолдер - елемент поля введення, в якому можна розмістити підказку. Коли користувач починає вводити дані, допоміжний текст пропадає, щоб не заважати. Кожен браузер має свою думку на рахунок того, як слід відображати цей елемент, і часом дефолтні стилі ламають весь дизайн. Щоб керувати ними, потрібно скористатися спеціальним правилом CSS placeholder.

Де знаходиться плейсхолдер?

Проблема в тому, що підказка поля введення надійно захована в тіньовому DOM, і дістатися до неї не так-то просто. Для цього використовується спеціальний нестандартний :: placeholder. З його допомогою можна управляти властивостями підказки.

Стилізація placeholder на CSS виглядає так:

Input :: placeholder (color: red; opacity: 1; font-style: italic;)

підтримка браузерами

Псевдоелемент CSS placeholder добре обробляється всіма сучасними браузерами, а для підтримки старих оглядачів можна скористатися префіксами:

  • :: - webkit-input-placeholder - для webkit-браузерів (Safari, Chrome, Opera);
  • :: - moz-placeholder - для браузерів Firefox вище 19 версії;
  • : -Moz-placeholder - для старих Firefox;
  • : -Ms-input-placeholder - для Internet Explorer вище 10 версії.

Як видно, старі браузери Mozilla, а також IE вважають placeholder CSS-псевдоклас, а не псевдоелементи. Не будемо з ними сперечатися, просто врахуємо цей аспект при стилізації поля введення.

можливості стилізації

Для псевдоелемента placeholder в CSS можна встановити наступні параметри:

  • фон - група блоку підказки поширюється на все поле введення. Можна задати не тільки колір (background-color), але і зображення (background-image).
  • колір тексту - color;
  • прозорість - opacity;
  • підкреслення, надкресленням або закреслення - text-decoration;
  • регістр - text-transform;
  • внутрішні відступи - padding. Підтримується не всіма браузерами. Як для малих елементів, верхній і нижній відступи ігноруються.
  • відображення шрифту - властивості групи font, line-height і різноманітні відступи (text-indent, letter-spacing, word-spacing);
  • вертикальне вирівнювання в рядку - vertical-align;
  • обрізка тексту при переповненні контейнера - text-overflow.
.input1 :: placeholder (background-image: linear-gradient (lime, blue); color: white;) .input2 :: placeholder (text-decoration: line-through; color: purple; font-weight: bold;). input3 :: placeholder (font-size: 16px; letter-spacing: 10px;) .input4 :: placeholder (background: brown; color: white; text-overflow: ellipsis;)

У фокусі

За замовчуванням підказка пропадає з поля введення тільки в тому випадку, якщо в нього введений хоча б один символ. Але placeholder дозволяє реалізувати зникнення відразу при фокусуванні на поле. Для цього необхідно поєднати його з псевдоклас: focus.

Input: focus :: placeholder (color: transparent;)

У деяких браузерах допустимо анімувати зміну ряду властивостей плейсхолдера за допомогою інструкції transition.

Input :: placeholder (color: black; transition: color 1s;) input: focus :: placeholder (color: white;)

У браузері Google Chrome колір підказки при фокусуванні на такому полі буде плавно змінюватися протягом однієї секунди.

Placeholder - псевдоклас або псевдоелемент, який відповідає за виведення назви поля. За своєю суттю це той тег (назвемо його так для простоти) в який ви вписуєте слово, а користувач бачить його всередині. Щось схоже на підказки або назви для кожного поля форми.

Кожен браузер обробляє цей тег за своїм, і стилі його оформлення залишають бажати кращого. Щоб змінити стилі за замовчуванням, достатньо додати пару рядків коду в файл стилів. Складного нічого немає.
Правда необхідно враховувати, що не всі ми зможемо поміняти.

Серед усього розмаїття стилів, в даному випадку нам доступні наступні речі:

  • font-weight - установка жирності тексту
  • font-size - вибір розміру тексту
  • font-family - вибір шрифту
  • background - фон і фонове зображення
  • color - колір тексту
  • word-spacing - установка інтервалу між словами
  • letter-spacing - установка інтервалу між буквами
  • text-decoration - вибір прикраси слів. Підкреслений, закреслений і тд
  • vertical-align - установка вертикального вирівнювання
  • text-transform - вибір зміни тексту. Все великими або малими літерами і тд
  • line-height - інтервал між рядками
  • text-indent - встановлює відступ по лівому краю у першого рядка параграфа
  • text-overflow - вибір відображення тексту, який не вміщується в блоці (приховати або обрізати і додати три крапки)
  • opacity - вибір прозорості елемента

Тепер, коли ми розібралися в доступних стилях, можна приступити до оформлення, для цього додамо наступні стилі:

:: - webkit-input-placeholder (color: # 2cb04d;)
:: - moz-placeholder (color: # 2cb04d;) / * Firefox 19+ * /
: -Moz-placeholder (color: # 2cb04d;) / * Firefox 18- * /
: -Ms-input-placeholder (color: # 2cb04d;)

Після додавання цих рядків, зміниться колір назв всередині полів форми і в кожному браузері він буде однаковий. Тут же можна дописати додаткові стилі.
Наприклад ось такий стиль

:: - webkit-input-placeholder (color: # 2cb04d; font-size: 1.5em; font-weight: 600;)
:: - moz-placeholder (color: # 2cb04d; font-size: 1.5em; font-weight: 600;) / * Firefox 19 + * /
: -Moz-placeholder (color: # 2cb04d; font-size: 1.5em; font-weight: 600;) / * Firefox 18 - * /
: -Ms-input-placeholder (color: # 2cb04d; font-size: 1.5em; font-weight: 600;)

Додасть колір, великий розмір і середню жирність тексту. Якщо додати додаткове властивість -
text-overflow: ellipsis то текст буде обрізатися за розміром поля, в кінці буде додано три крапки.

Є ще одна цікава властивість, завдяки появі анімації в css (стилях) можна налаштувати гарне приховування при установці курсора в поле. Раніше це робилося черз js (скрипти)

Input :: - webkit-input-placeholder (opacity: 1; transition: opacity 0.3s ease;)
.input :: - moz-placeholder (opacity: 1; transition: opacity 0.3s ease;)
.input: -moz-placeholder (opacity: 1; transition: opacity 0.3s ease;)
.input: -ms-input-placeholder (opacity: 1; transition: opacity 0.3s ease;)
.input: focus :: - webkit-input-placeholder (opacity: 0; transition: opacity 0.3s ease;)
.input: focus :: - moz-placeholder (opacity: 0; transition: opacity 0.3s ease;)
.input: focus: -moz-placeholder (opacity: 0; transition: opacity 0.3s ease;)
.input: focus: -ms-input-placeholder (opacity: 0; transition: opacity 0.3s ease;)

Додавання таких стилів дозволить зробити плавне зникнення placeholder-a при установки курсору в поле
.input - це клас елемента форми. Для того щоб стилі спрацювали, код поля форми повинен виглядати так:

Або можна використовувати клас елемента. Таким чином можна задавати різні стилі для кожної форми.


.contacts-form form input :: - webkit-input-placeholder (color: # 2cb04d; font-size: 1.5em; font-weight: 600;)
.contacts-form form input :: - moz-placeholder (color: # 2cb04d; font-size: 1.5em; font-weight: 600;) / * Firefox 19 + * /
.contacts-form form input: -moz-placeholder (color: # 2cb04d; font-size: 1.5em; font-weight: 600;) / * Firefox 18 - * /
.contacts-form form input: -ms-input-placeholder (color: # 2cb04d; font-size: 1.5em; font-weight: 600;)

Ось такими нехитрими способами можна зробити дійсно гарне оформлення форми.

Зазвичай атрибут placeholder в input і textarea використовується для заклику до дії всередині цих елементів. У цій замітці опишу кілька варіантів стилізації тексту placeholder-ів, а також варіанти їх анімації

Отже, колір тексту нашого placeholder-а можна змінити використавши, наприклад наступний набір css-правил:

:: - webkit-input-placeholder (color: # c0392b;) :: - moz-placeholder (color: # c0392b;) / * Firefox 19+ * /: -moz-placeholder (color: # c0392b;) / * Firefox 18- * /: -ms-input-placeholder (color: # c0392b;)

Об'ємність коду для стилізації такого простого властивості обумовлена ​​отсутсівтемотсутствіем загального стандарту, в зв'язку з чим кожен браузер по-своєму реалізував підтримку стилізації placeholder-а.

Крім того, підтримуються не всі css властивості. Ось перелік точно поддерживаемих властивостей:

font (і пов'язані)
background (і пов'язані)
color
word-spacing
letter-spacing
text-decoration
vertical-align
text-transform
line-height
text-indent
text-overflow
opacity

Також буває так, що текст плейсхолдера «виходить» за межі ширини елемента input або textarea (частий випадок для мобільних пристроїв). При цьому він автоматично некрасиво обрізається.

Виправити цю неприємність нам допоможе таке css-властивість, як text-overflow: ellipsis, яке додасть естетичне троееточіе до обрізаному ділянці placeholder-a. У стилях прописуємо ось так:

input [placeholder] (text-overflow: ellipsis;) input :: - moz-placeholder (text-overflow: ellipsis;) input: -moz-placeholder (text-overflow: ellipsis;) input: -ms-input-placeholder ( text-overflow: ellipsis;)

Для додання ще більшої естетики нашим placeholder-ам є можливість додати ефект його приховування при отриманні фокусу відповідного елемента.

Кілька прикладів такого приховування з елементами анімації:

/ * Плавне зміна прозорості placeholder-а при фокусі * /.input :: - webkit-input-placeholder (opacity: 1; transition: opacity 0.3s ease;) .input :: - moz-placeholder (opacity: 1; transition: opacity 0.3s ease;) .input: -moz- placeholder (opacity: 1; transition: opacity 0.3s ease;) .input: -ms-input-placeholder (opacity: 1; transition: opacity 0.3s ease;) .input (opacity: 0; transition: opacity 0.3s ease; ) .input: focus :: - moz-placeholder (opacity: 0; transition: opacity 0.3s ease;) .input: focus: -moz-placeholder (opacity: 0; transition: opacity 0.3s ease;) .input: focus : -ms-input-placeholder (opacity: 0; transition: opacity 0.3s ease;) / * Зрушення placeholder-а вправо при фокусі * /.input :: - webkit-input-placeholder (text-indent: 0px; transition: text-indent 0.3s ease;) .input :: - moz-placeholder (text-indent: 0px; transition: text-indent 0.3s ease ;) .input: -moz-placeholder (text-indent: 0px; transition: text-indent 0.3s ease;) .input: -ms-input-placeholder (text-indent: 0px; transition: text-indent 0.3s ease ;) .input : Focus :: - webkit-input-placeholder(Text-indent: 500px; transition: text-indent 0.3s ease;) .input: focus :: - moz-placeholder (text-indent: 500px; transition: text-indent 0.3s ease;) .input: focus: - moz-placeholder (text-indent: 500px; transition: text-indent 0.3s ease;) .input: focus: -ms-input-placeholder (text-indent: 500px; transition: text-indent 0.3s ease;) / * Зрушення placeholder-а вниз при фокусі * /.input :: - webkit-input-placeholder (line-height: 20px; transition: line-height 0.5s ease;) .input :: - moz-placeholder (line-height: 20px; transition: line-height 0.5s ease ;) .input: -moz-placeholder (line-height: 20px; transition: line-height 0.5s ease;) .input: -ms-input-placeholder (line-height: 20px; transition: line-height 0.5s ease ;) .input : Focus :: - webkit-input-placeholder(Line-height: 100px; transition: line-height 0.5s ease;) .input: focus :: - moz-placeholder (line-height: 100px; transition: line-height 0.5s ease;) .input: focus: - moz-placeholder (line-height: 100px; transition: line-height 0.5s ease;) .input: focus: -ms-input-placeholder (line-height: 100px; transition: line-height 0.5s ease;)

На цьому і закінчимо.

Placeholders, those frequently grayed out text elements inside an input, can be a pain to style. Fortunately we "ve sourced a short but effective CSS solution to style your input" s placeholder text any color and opacity you wish. Read on for the code.

Changing placeholder text color

Let "s start with a simple input and some placeholder text, for this example we" ll use the word "search" but you can use anything you want. The basic HTML is below:

HTML

Input (and textarea) placeholder text defaults to a light gray color, however, we can change that with a few lines of CSS. Here we "ll color the input text red using an HTML color name, but any color method will suffice (HEX, RGB, HSL).

CSS
:: - webkit-input-placeholder (/ * Chrome * / color: red;): -ms-input-placeholder (/ * IE 10+ * / color: red;) :: - moz-placeholder (/ * Firefox 19 + * / color: red; opacity: 1;): -moz-placeholder (/ * Firefox 4 - 18 * / color: red; opacity: 1;)

Note that it "s important to include the different vendor prefixes in order to support as many browsers as possible. Only Firefox" s input placeholder text defaults to a slight transparency so its unnecessary to set the opacity property on IE or Chrome.

Changing placeholder focus text color

Alright, we "ve successfully changed the color of the placeholder text to red, but it would be nice if something happened when a user clicks inside our input. Using the same vendor prefixed CSS properties, we can alter the opacity of the input placeholder text on focus.

CSS
input (outline: none; padding: 12px; border-radius: 3px; border: 1px solid black;) :: - webkit-input-placeholder (/ * Chrome * / color: red; transition: opacity 250ms ease-in-out ;): focus :: - webkit-input-placeholder (opacity: 0.5;): -ms-input-placeholder (/ * IE 10+ * / color: red; transition: opacity 250ms ease-in-out;): focus : -ms-input-placeholder (opacity: 0.5;) :: - moz-placeholder (/ * Firefox 19+ * / color: red; opacity: 1; transition: opacity 250ms ease-in-out;): focus :: -moz-placeholder (opacity: 0.5;): -moz-placeholder (/ * Firefox 4 - 18 * / color: red; opacity: 1; transition: opacity 250ms ease-in-out;): focus: -moz-placeholder (opacity: 0.5;)

In the example above we "ve thrown in a few basic styles on the input itself, and added a transition on the opacity to make the experience just a little nicer. Check out the demo and experiment with other CSS properties and transitions.