Как изменить цвет placeholder html

Chrome supports the placeholder attribute on input[type=text] elements (others probably do too). But the following CSS doesn't do anything to the placeholder's value: input[placeholder], [place...

Chrome supports the placeholder attribute on input[type=text] elements (others probably do too).

But the following CSS doesn’t do anything to the placeholder’s value:

input[placeholder], [placeholder], *[placeholder] {
    color: red !important;
}
<input type="text" placeholder="Value">

But Value will still remain grey instead of red.

Is there a way to change the color of the placeholder text?

8

Implementation

There are three different implementations: pseudo-elements, pseudo-classes, and nothing.

  • WebKit, Blink (Safari, Google Chrome, Opera 15+) and Microsoft Edge are using a pseudo-element: ::-webkit-input-placeholder. [Ref]
  • Mozilla Firefox 4 to 18 is using a pseudo-class: :-moz-placeholder (one colon). [Ref]
  • Mozilla Firefox 19+ is using a pseudo-element: ::-moz-placeholder, but the old selector will still work for a while. [Ref]
  • Internet Explorer 10 and 11 are using a pseudo-class: :-ms-input-placeholder. [Ref]
  • April 2017: Most modern browsers support the simple pseudo-element ::placeholder [Ref]

Internet Explorer 9 and lower does not support the placeholder attribute at all, while Opera 12 and lower do not support any CSS selector for placeholders.

The discussion about the best implementation is still going on. Note the pseudo-elements act like real elements in the Shadow DOM. A padding on an input will not get the same background color as the pseudo-element.

CSS selectors

User agents are required to ignore a rule with an unknown selector. See Selectors Level 3:

a group of selectors containing an invalid selector is invalid.

So we need separate rules for each browser. Otherwise the whole group would be ignored by all browsers.

::-webkit-input-placeholder { /* WebKit, Blink, Edge */
    color:    #909;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
   color:    #909;
   opacity:  1;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
   color:    #909;
   opacity:  1;
}
:-ms-input-placeholder { /* Internet Explorer 10-11 */
   color:    #909;
}
::-ms-input-placeholder { /* Microsoft Edge */
   color:    #909;
}

::placeholder { /* Most modern browsers support this now. */
   color:    #909;
}
<input placeholder="Stack Snippets are awesome!">

Usage notes

  • Be careful to avoid bad contrasts. Firefox’s placeholder appears to be defaulting with a reduced opacity, so needs to use opacity: 1 here.
  • Note that placeholder text is just cut off if it doesn’t fit – size your input elements in em and test them with big minimum font size settings. Don’t forget translations: some languages need more room for the same word.
  • Browsers with HTML support for placeholder but without CSS support for that (like Opera) should be tested too.
  • Placeholders are no replacement for labels, so make sure you have a label, too
  • Some browsers use additional default CSS for some input types (email, search). These might affect the rendering in unexpected ways. Use the properties -webkit-appearance and -moz-appearance to change that. Example:
    [type="search"] {
        -moz-appearance:    textfield;
        -webkit-appearance: textfield;
        appearance: textfield;
    }

Andy's user avatar

Andy

4,0802 gold badges24 silver badges47 bronze badges

answered Apr 9, 2010 at 20:36

fuxia's user avatar

0

/* do not group these rules */
*::-webkit-input-placeholder {
    color: red;
}
*:-moz-placeholder {
    /* FF 4-18 */
    color: red;
    opacity: 1;
}
*::-moz-placeholder {
    /* FF 19+ */
    color: red;
    opacity: 1;
}
*:-ms-input-placeholder {
    /* IE 10+ */
    color: red;
}
*::-ms-input-placeholder {
    /* Microsoft Edge */
    color: red;
}
*::placeholder {
    /* modern browser */
    color: red;
}
<input placeholder="hello"/> <br />
<textarea placeholder="hello"></textarea>

This will style all input and textarea placeholders.

Important Note: Do not group these rules. Instead, make a separate rule for every selector (one invalid selector in a group makes the whole group invalid).

0

You may also want to style textareas:

input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
  color: #FF9900;
}

input:-moz-placeholder,
textarea:-moz-placeholder {
  color: #FF9900;
}
<textarea rows="4" cols="50" placeholder="Stack Snippets are nice!">
</textarea>

0

For Bootstrap and Less users, there is a mixin .placeholder:

// Placeholder text
// -------------------------
.placeholder(@color: @placeholderText) {
  &:-moz-placeholder {
    color: @color;
  }
  &:-ms-input-placeholder {
    color: @color;
  }
  &::-webkit-input-placeholder {
    color: @color;
  }
}

Peter Mortensen's user avatar

answered Jun 6, 2013 at 8:47

EIIPII's user avatar

EIIPIIEIIPII

1,7711 gold badge17 silver badges10 bronze badges

1

In addition to toscho’s answer I’ve noticed some webkit inconsistencies between Chrome 9-10 and Safari 5 with the CSS properties supported that are worth noting.

Specifically Chrome 9 and 10 do not support background-color, border, text-decoration and text-transform when styling the placeholder.

The full cross-browser comparison is here.

answered Feb 9, 2011 at 16:44

ajcw's user avatar

ajcwajcw

23.5k6 gold badges29 silver badges47 bronze badges

For Sass users:

// Create placeholder mixin
@mixin placeholder($color, $size:"") {
  &::-webkit-input-placeholder {
    color: $color;
    @if $size != "" {
      font-size: $size;
    }
  }
  &:-moz-placeholder {
    color: $color;
    @if $size != "" {
      font-size: $size;
    }
  }
  &::-moz-placeholder {
    color: $color;
    @if $size != "" {
      font-size: $size;
    }
  }
  &:-ms-input-placeholder {
    color: $color;
    @if $size != "" {
      font-size: $size;
    }
  }
}

// Use placeholder mixin (the size parameter is optional)
[placeholder] {
  @include placeholder(red, 10px);
}

0

This will work fine. DEMO HERE:

input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
  color: #666;
}
input:-moz-placeholder,
textarea:-moz-placeholder {
  color: #666;
}
input::-moz-placeholder,
textarea::-moz-placeholder {
  color: #666;
}
input:-ms-input-placeholder,
textarea:-ms-input-placeholder {
  color: #666;
}
<input type="text" placeholder="Value" />

answered Sep 14, 2013 at 12:52

Love Trivedi's user avatar

Love TrivediLove Trivedi

3,8193 gold badges19 silver badges26 bronze badges

0

In Firefox and Internet Explorer, the normal input text color overrides the color property of placeholders. So, we need to

::-webkit-input-placeholder { 
    color: red; text-overflow: ellipsis; 
}
:-moz-placeholder { 
    color: #acacac !important; text-overflow: ellipsis; 
}
::-moz-placeholder { 
    color: #acacac !important; text-overflow: ellipsis; 
} /* For the future */
:-ms-input-placeholder { 
    color: #acacac !important; text-overflow: ellipsis; 
}

Peter Mortensen's user avatar

answered Feb 14, 2013 at 21:11

Dionysios Arvanitis's user avatar

0

CSS provides the ::placeholder pseudo-element.

Note that the .placeholder mixin from Bootstrap is deprecated in favor of this.

Example:

input::placeholder { color: black; }

When using autoprefixer the above will be converted to the correct code for all browsers.

1

Cross-browser solution:

/* all elements */
::-webkit-input-placeholder { color:#f00; }
::-moz-placeholder { color:#f00; } /* firefox 19+ */
:-ms-input-placeholder { color:#f00; } /* ie */
input:-moz-placeholder { color:#f00; }

/* individual elements: 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; }

/* individual elements: 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; }

Credit: David Walsh

0

Now we have a standard way to apply CSS to an input’s placeholder : ::placeholder pseudo-element from this CSS Module Level 4 Draft.

1

I just realize something for Mozilla Firefox 19+ that the browser gives an opacity value for the placeholder, so the color will not be what you really want.

input::-webkit-input-placeholder, textarea::-webkit-input-placeholder {
    color: #eee; opacity:1;
}
input:-moz-placeholder, textarea:-moz-placeholder {
    color: #eee; opacity:1;
}
input::-moz-placeholder, textarea::-moz-placeholder {
    color: #eee; opacity:1;
}
input:-ms-input-placeholder, textarea:-ms-input-placeholder {
    color: #eee; opacity:1;
}

I overwrite the opacity for 1, so it will be good to go.

I don’t remember where I’ve found this code snippet on the Internet (it wasn’t written by me, don’t remember where I’ve found it, nor who wrote it).

$('[placeholder]').focus(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
        }
    }).blur(function() {
        var input = $(this);
        if (input.val() == '' || input.val() == input.attr('placeholder')) {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
        }
    }).blur();
    $('[placeholder]').parents('form').submit(function() {
        $(this).find('[placeholder]').each(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
            }
        })
    });

Just load this JavaScript code and then edit your placeholder with CSS by calling this rule:

form .placeholder {
   color: #222;
   font-size: 25px;
   /* etc. */
}

Peter Mortensen's user avatar

answered Apr 14, 2013 at 2:28

Dragos Rizescu's user avatar

Dragos RizescuDragos Rizescu

3,3405 gold badges31 silver badges42 bronze badges

2

For Bootstrap users, if you are using class="form-control", there may be a CSS specificity issue. You should get a higher priority:

.form-control::-webkit-input-placeholder {
    color: red;
}
//.. and other browsers

Or if you are using Less:

.form-control{
    .placeholder(red);
}

0

I think this code will work because a placeholder is needed only for input type text. So this one line CSS will be enough for your need:

input[type="text"]::-webkit-input-placeholder {
    color: red;
}

Peter Mortensen's user avatar

answered Jun 25, 2015 at 9:01

Alias Varghese's user avatar

Alias VargheseAlias Varghese

2,0322 gold badges23 silver badges52 bronze badges

1

If you are using Bootstrap and couldn’t get this working then probably you missed the fact that Bootstrap itself adds these selectors. This is Bootstrap v3.3 we are talking about.

If you are trying to change the placeholder inside a .form-control CSS class then you should override it like this:

.form-control::-webkit-input-placeholder { /* WebKit, Blink, Edge */
    color:    #777;
}
.form-control:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color:    #777;
    opacity:  1;
}
.form-control::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #777;
    opacity:  1;
}
.form-control:-ms-input-placeholder { /* Internet Explorer 10-11 */
    color:    #777;
}

How about this

<input type="text" value="placeholder text" onfocus="this.style.color='#000'; 
    this.value='';" style="color: #f00;" />

No CSS or placeholder, but you get the same functionality.

Mobarak Ali's user avatar

answered Oct 8, 2012 at 19:21

user1729061's user avatar

user1729061user1729061

4873 silver badges4 bronze badges

4

This short and clean code:

::-webkit-input-placeholder {color: red;}
:-moz-placeholder           {color: red; /* For Firefox 18- */}
::-moz-placeholder          {color: red; /* For Firefox 19+ */}
:-ms-input-placeholder      {color: red;}

I have tried every combination here to change the color, on my mobile platform, and eventually it was:

-webkit-text-fill-color: red;

which did the trick.

1

Adding an actual very nice and simple possibility: CSS filters!

enter image description here

enter image description here

enter image description here

It will style everything, including the placeholder.

The following will set both input elements on the same palette, using the hue filter for color changes. It render very well now in browsers (except ie…)

input {
  filter: sepia(100%) saturate(400%) grayscale(0) contrast(200%) hue-rotate(68deg) invert(18%);
}
<input placeholder="Hello world!" />
<input type="date" /><br>
<input type="range" />
<input type="color" />

To allow users to change it dynamically, using an input type color for changes, or to find nuances, check out this snippet:

From: Codepen

function stylElem() {
  stylo.dataset.hue = ((parseInt(stylo.value.substring(1), 16))/46666).toFixed(0)
  Array.from(document.querySelectorAll('input, audio, video')).forEach(function(e){
      e.style.cssText += ";filter:sepia(100%) saturate(400%)grayscale(0)contrast(200%)hue-rotate("+ stylo.dataset.hue+"deg)invert("+(stylo.dataset.hue/3.6)+"%)"
  out.innerText = e.style.cssText
})()}

stylElem()
body {background: black; color: white}
Choose a color!
<input type="color" id="stylo" oninput="stylElem()">
<br>
<div id="out"></div> <p>
  <input placeholder="Hello world!" />
  <input type="date" /><br>
  <input type="range" />
 <br>
<audio controls src="#"></audio> <br><br> 
<video controls src="#"></video>

Css filters docs: https://developer.mozilla.org/en-US/docs/Web/CSS/filter

0

For SASS/SCSS user using Bourbon, it has a built-in function.

//main.scss
@import 'bourbon';

input {
  width: 300px;

  @include placeholder {
    color: red;
  }
}

CSS Output, you can also grab this portion and paste into your code.

//main.css

input {
  width: 300px;
}

input::-webkit-input-placeholder {
  color: red;
}
input:-moz-placeholder {
  color: red;
}
input::-moz-placeholder {
  color: red;
}
input:-ms-input-placeholder {
  color: red;
}

try this code for different input element different style

your css selector::-webkit-input-placeholder { /*for webkit */
    color:#909090;
    opacity:1;
}
 your css selector:-moz-placeholder { /*for mozilla */
    color:#909090;
    opacity:1;
}
 your css selector:-ms-input-placeholder { /*for for internet exprolar */ 
   color:#909090;
   opacity:1;
}

example 1:

input[type="text"]::-webkit-input-placeholder { /*for webkit */
    color: red;
    opacity:1;
}
 input[type="text"]:-moz-placeholder { /*for mozilla */
    color: red;
    opacity:1;
}
 input[type="text"]:-ms-input-placeholder { /*for for internet exprolar */ 
   color: red;
   opacity:1;
}

example 2:

input[type="email"]::-webkit-input-placeholder { /*for webkit */
    color: gray;
    opacity:1;
}
 input[type="email"]:-moz-placeholder { /*for mozilla */
    color: gray;
    opacity:1;
}
 input[type="email"]:-ms-input-placeholder { /*for for internet exprolar */ 
   color: gray;
   }

This is fine for most of the modern browsers

input::placeholder{
  color: red; // css implementation
}

Just in case if you are using SCSS

input {
  &::placeholder {
    color: red; // scss
  }
}

Here is one more example:

.form-control::-webkit-input-placeholder {
  color: red;
  width: 250px;
}
h1 {
  color: red;
}
<div class="col-sm-4">
  <input class="form-control" placeholder="Enter text here.." ng-model="Email" required/>
</div>

You can change an HTML5 input’s placeholder color with CSS. If by chance, your CSS conflict, this code note working , you can use (!important) like below.

::-webkit-input-placeholder { /* WebKit, Blink, Edge */
    color:#909 !important;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
   color:#909 !important;
   opacity:1 !important;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
   color:#909 !important;
   opacity:1 !important;
}
:-ms-input-placeholder { /* Internet Explorer 10-11 */
   color:#909 !important;
}
::-ms-input-placeholder { /* Microsoft Edge */
   color:#909 !important;
}

<input placeholder="Stack Snippets are awesome!">

Hope this will help.

OK, placeholders behave differently in different browsers, so you need using browser prefix in your CSS to make them identical, for example Firefox gives a transparency to placeholder by default, so need to add opacity 1 to your css, plus the color, it’s not a big concern most of the times, but good to have them consistent:

*::-webkit-input-placeholder { /* WebKit browsers */
    color:    #ccc;
}
*:-moz-placeholder { /* Mozilla Firefox <18 */
    color:    #ccc;
    opacity:  1;
}
*::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #ccc;
    opacity:  1;
}
*:-ms-input-placeholder { /* Internet Explorer 10-11 */
    color:    #ccc;
}

You can use this for input and focus style:

input::-webkit-input-placeholder  { color:#666;}
input:-moz-placeholder  { color:#666;}
input::-moz-placeholder { color:#666;}
input:-ms-input-placeholder  { color:#666;}
/* focus */
input:focus::-webkit-input-placeholder { color:#eee; }
input:focus:-moz-placeholder { color:#eee } /* FF 4-18 */
input:focus::-moz-placeholder { color:#eee } /* FF 19+ */
input:focus:-ms-input-placeholder { color:#eee } /* IE 10+ */

The easiest way would be:

#yourInput::placeholder {
    color: red;/*As an example*/
}
/* if that would not work, you can always try styling the attribute itself: */
#myInput[placeholder] {
    color: red;
}

Here is the solution with CSS selectors

::-webkit-input-placeholder { /* WebKit, Blink, Edge */
    color:    #909;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
   color:    #909;
   opacity:  1;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
   color:    #909;
   opacity:  1;
}
::-ms-input-placeholder { /* Microsoft Edge */
   color:    #909;
}
:-ms-input-placeholder { /* Internet Explorer 10-11 */
   color:    #909;
}
  • WebKit, Blink (Safari, Google Chrome, Opera 15+) and Microsoft Edge are using a pseudo-element:
    ::-webkit-input-placeholder.
  • Mozilla Firefox 4 to 18 is using a pseudo-class:
    :-moz-placeholder (one colon).
    Mozilla Firefox 19+ is using a pseudo-element:
    ::-moz-placeholder, but the old selector will still work for a while.
  • Internet Explorer 10 and 11 are using a pseudo-class:
    :-ms-input-placeholder.
  • Internet Explorer 9 and lower does not support the placeholder attribute at all, while Opera 12 and lower do not support any CSS selector for placeholders.
::placeholder{
  color: red;
}
<input type="text" placeholder="Value">

CSS псевдоэлемент ::placeholder представляет собой текст placeholder (en-US) в <input> или <textarea> (en-US) элементах.

::placeholder {
  color: blue;
  font-size: 1.5em;
}

В ::placeholder можно использовать только те CSS-свойства, которые разрешены в псевдоэлементе ::first-line.

Примечание: В большинстве браузеров по умолчанию placeholder выглядит как полупрозрачный или светло-серый текст.

Синтаксис

Error: could not find syntax for this item

Примеры

Красный текст

HTML

<input placeholder="Введите что-нибудь!">

CSS

input::placeholder {
  color: red;
  font-size: 1.2em;
  font-style: italic;
}

Результат

Зелёный текст

HTML

<input placeholder="Введите что-нибудь...">

CSS

input::placeholder {
  color: green;
}

Результат

Проблемы доступности

Цветовой контраст

Контрастность

Текст placeholder обычно имеет более светлую расцветку и содержит информацию о том, какие введённые данные будут допустимы, но при этом не является текущими введёнными данными.

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

Коэффициент цветового контраста определяется путём сравнения яркости текста placeholder и цветом фона формы ввода. Чтобы соответствовать рекомендациям Web Content Accessibility Guidelines (WCAG), требуется соотношение 4.5:1 для основного текста и 3:1 для более крупного текста, например, заголовков. Крупный текст определяется как 18.66px и больше с жирным начертанием или 24px и больше с обычным начертанием.

  • WebAIM: Color Contrast Checker
  • MDN Understanding WCAG, Guideline 1.4 explanations
  • Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0

Использование

Текст placeholder с высоким цветовым контрастом может быть воспринят как введённые данные. Текст placeholder исчезает, когда пользователь вводит что-либо в <input> элемент. Эти обстоятельства могут помешать заполнить правильно форму, особенно людям с когнитивными проблемами.

Другой подход к представлению информации placeholder заключается в том, чтобы расположить её вне формы ввода в непосредственной близости от неё, а затем использовать aria-describedby для программного связывания <input> элемента с подсказкой.

В таком случае содержимое подсказки будет доступно даже в том случае, если что-то введено в форму. Большинство скринридеров используют aria-describedby для чтения подсказок после того, как будет прочитан текст метки формы. Пользователь может отключить эту функцию, если дополнительная информация окажется ему ненужной.

<label for="user-email">Ваш email адрес</label>
<span id="user-email-hint" class="input-hint">Пример: 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

Текст placeholder будет отображаться с теми же стилями, что и введённый пользователем текст при работе в режиме высокой контрастности Windows (en-US). Это вызовет затруднения с определением того какой текст был введён, а какой является placeholder.

  • Greg Whitworth — How to use -ms-high-contrast

Метки

Placeholder не является заменой элемента <label>. Без метки, которая программно связывается с формой с помощью for и id атрибутов, такие программы, как скринридеры не смогут анализировать элементы <input>.

  • MDN Basic form hints (en-US)
  • Placeholders in Form Fields Are Harmful — Nielsen Norman Group

Спецификации

Specification
CSS Pseudo-Elements Module Level 4
# placeholder-pseudo

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

  • Псевдокласс :placeholder-shown, который позволяет применять стили к элементу с активным placeholder.
  • Связанные HTML-элементы: <input>, <textarea> (en-US)
  • HTML-формы

Цвет замещающего текста

В HTML5 к полям формы добавлен атрибут placeholder, который устанавливает замещающий текст. Такой текст отображается серым цветом и пропадает, когда поле получает фокус. Использование этого атрибута достаточно просто, следует только написать текст, всё остальное браузер берет на себя.

<input placeholder=»Текст»>

Серый цвет, используемый по умолчанию, выбран удачно, но не всегда вписывается в дизайн страницы, особенно если меняется цвет фона полей формы, как показано в примере 1.

Пример 1. Использование placeholder

HTML5CSS 2.1IECrOpSaFx

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title>placeholder</title>
  <style>
   body {background: #053f38; color: #98baba; }
   input[type="search"] { 
    padding: 3px;
    background: #333;
    color: #053f38;
    border: 1px solid #ccc;
   }
  </style>
 </head>
 <body> 
  <form action="handler.php">
   <p><input type="search" placeholder="Поиск по сайту" />
   <input type="submit" value="Искать"></p>
  </form>
</body>
</html>

Для изменения цвета текста в атрибуте placeholder в Firefox применяется псевдокласс ::-moz-placeholder.

input::-moz-placeholder { color: red; }

В Safari и Chrome стиль текста меняется следующим образом.

input::-webkit-input-placeholder { color: red; }

Таким образом, соединяя воедино этот стиль, получим страницу, одинаково работающую в браузерах Firefox, Safari и Chrome (пример 2).

Пример 2. Цвет текста

HTML5CSS3IECrOpSaFx

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title>placeholder</title>
  <style>
   body {background: #053f38; color: #98baba; }
   input[type="search"] { 
    padding: 3px;
    background: #333;
    color: #053f38;
    border: 1px solid #ccc;
   }
   input[type="search"]::-webkit-input-placeholder {
    color: #ccc;
   } 
   input[type="search"]::-moz-placeholder {
    color: #ccc;
   }
  </style>
 </head>
 <body> 
  <form action="handler.php">
   <p><input type="search" placeholder="Поиск по сайту" />
   <input type="submit" value="Искать"></p>
  </form>
</body>
</html>

Браузеры «не любят» группировать такой стиль, поэтому мне пришлось для отдельных браузеров повторить конструкцию.

Теперь что касается других браузеров. Internet Explorer вообще не понимает атрибут placeholder и отказывается с ним что-либо делать, а Opera не умеет менять цвет текста через стили. Так что приведённый трюк работает только в Firefox, Safari и Chrome.

placeholder-css

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

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

html

<input type="text" placeholder="Оставьте сообщение здесь">

input placeholder demo

Стиль 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 – псевдоэлементом.

Смотрим, что получилось:

input placeholder demo

Нужно сказать, что поддерживаются не все возможные 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]          {text-overflow:ellipsis;}
input::-moz-placeholder     {text-overflow:ellipsis;} 
input:-moz-placeholder      {text-overflow:ellipsis;} 
input:-ms-input-placeholder {text-overflow:ellipsis;}    

input placeholder demo

Как скрыть 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}

input placeholder demo

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

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

input placeholder demo

Вот сss:

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-placeholder            {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-placeholder           {line-height: 100px; transition: line-height 0.5s ease;}
.input3:focus:-ms-input-placeholder      {line-height: 100px; transition: line-height 0.5s ease;}

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

Is that possible to set the color of placeholder text ?

<textarea placeholder="Write your message here..."></textarea>

asked Apr 30, 2011 at 3:25

Misha Moroshko's user avatar

Misha MoroshkoMisha Moroshko

163k224 gold badges498 silver badges733 bronze badges

2

::-webkit-input-placeholder { /* WebKit browsers */
    color:    #999;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color:    #999;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #999;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
    color:    #999;
}

answered Mar 5, 2013 at 14:09

HasanAboShally's user avatar

HasanAboShallyHasanAboShally

18.4k7 gold badges29 silver badges34 bronze badges

Nobody likes the «refer to this answer» answers, but in this case it may help: Change an HTML5 input’s placeholder color with CSS

Since it’s only supported by a couple of browsers, you can try the jQuery placeholder plugin (assuming you canare using jQuery). It allows you to style the placeholder text via CSS since it’s really only a swap trick it does with focus events.

The plugin does not activate on browsers that support it, though, so you can have CSS that targets chromefirefox and the jQuery plugin’s CSS to catch the rest.

The plugin can be found here: https://github.com/mathiasbynens/jquery-placeholder

Community's user avatar

answered Apr 30, 2011 at 3:31

Vassi's user avatar

Try this

textarea::-webkit-input-placeholder {  color: #999;}

answered Aug 20, 2012 at 6:29

Suresh Pattu's user avatar

Suresh PattuSuresh Pattu

5,96815 gold badges58 silver badges91 bronze badges

For giving placeholder a color just use these lines of code:

::-webkit-input-placeholder { color: red; }
::-moz-placeholder {color: red; }
:-ms-input-placeholder { color: red; } 
:-o-input-placeholder { color: red; } 

nobody's user avatar

nobody

19.7k17 gold badges56 silver badges77 bronze badges

answered Feb 16, 2015 at 18:27

daraptoor's user avatar

daraptoordaraptoor

1313 silver badges10 bronze badges

2

#Try this:

input[type="text"],textarea[type="text"]::-webkit-input-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]:-moz-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]::-moz-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]:-ms-input-placeholder {
    color:#f51;
}

##Works very well for me.

answered Jan 21, 2015 at 7:18

Ankit Pundhir's user avatar

Try this

input::-webkit-input-placeholder { /* WebKit browsers */
    color:    #f51;
}
input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color:    #f51;
}
input::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #f51;
}
input:-ms-input-placeholder { /* Internet Explorer 10+ */
    color:    #f51;
}
<input type="text" placeholder="Value" />

Pieter Goosen's user avatar

answered Nov 17, 2014 at 5:20

Altynbek S.'s user avatar

1

For Firefox use:

 input:-moz-placeholder { color: #aaa; }
 textarea:-moz-placeholder { color: #aaa;}

For all other browsers (Chrome, IE, Safari), just use:

 .placeholder { color: #aaa; }

answered Feb 5, 2013 at 4:44

skidadon's user avatar

skidadonskidadon

5474 silver badges7 bronze badges

4

Is that possible to set the color of placeholder text ?

<textarea placeholder="Write your message here..."></textarea>

asked Apr 30, 2011 at 3:25

Misha Moroshko's user avatar

Misha MoroshkoMisha Moroshko

163k224 gold badges498 silver badges733 bronze badges

2

::-webkit-input-placeholder { /* WebKit browsers */
    color:    #999;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color:    #999;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #999;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
    color:    #999;
}

answered Mar 5, 2013 at 14:09

HasanAboShally's user avatar

HasanAboShallyHasanAboShally

18.4k7 gold badges29 silver badges34 bronze badges

Nobody likes the «refer to this answer» answers, but in this case it may help: Change an HTML5 input’s placeholder color with CSS

Since it’s only supported by a couple of browsers, you can try the jQuery placeholder plugin (assuming you canare using jQuery). It allows you to style the placeholder text via CSS since it’s really only a swap trick it does with focus events.

The plugin does not activate on browsers that support it, though, so you can have CSS that targets chromefirefox and the jQuery plugin’s CSS to catch the rest.

The plugin can be found here: https://github.com/mathiasbynens/jquery-placeholder

Community's user avatar

answered Apr 30, 2011 at 3:31

Vassi's user avatar

Try this

textarea::-webkit-input-placeholder {  color: #999;}

answered Aug 20, 2012 at 6:29

Suresh Pattu's user avatar

Suresh PattuSuresh Pattu

5,96815 gold badges58 silver badges91 bronze badges

For giving placeholder a color just use these lines of code:

::-webkit-input-placeholder { color: red; }
::-moz-placeholder {color: red; }
:-ms-input-placeholder { color: red; } 
:-o-input-placeholder { color: red; } 

nobody's user avatar

nobody

19.7k17 gold badges56 silver badges77 bronze badges

answered Feb 16, 2015 at 18:27

daraptoor's user avatar

daraptoordaraptoor

1313 silver badges10 bronze badges

2

#Try this:

input[type="text"],textarea[type="text"]::-webkit-input-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]:-moz-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]::-moz-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]:-ms-input-placeholder {
    color:#f51;
}

##Works very well for me.

answered Jan 21, 2015 at 7:18

Ankit Pundhir's user avatar

Try this

input::-webkit-input-placeholder { /* WebKit browsers */
    color:    #f51;
}
input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color:    #f51;
}
input::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #f51;
}
input:-ms-input-placeholder { /* Internet Explorer 10+ */
    color:    #f51;
}
<input type="text" placeholder="Value" />

Pieter Goosen's user avatar

answered Nov 17, 2014 at 5:20

Altynbek S.'s user avatar

1

For Firefox use:

 input:-moz-placeholder { color: #aaa; }
 textarea:-moz-placeholder { color: #aaa;}

For all other browsers (Chrome, IE, Safari), just use:

 .placeholder { color: #aaa; }

answered Feb 5, 2013 at 4:44

skidadon's user avatar

skidadonskidadon

5474 silver badges7 bronze badges

4

Понравилась статья? Поделить с друзьями:

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

  • Как изменить цвет pagination swiper
  • Как изменить цвет padding html
  • Как изменить цвет outline
  • Как изменить цвет office 2019
  • Как изменить цвет office 2007

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии