Change an HTML5 input's placeholder color with CSS

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">

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!">

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

    您可能还想要设计textareas:

    input::-webkit-input-placeholder, textarea::-webkit-input-placeholder {
      color: #636363;
    }
    input:-moz-placeholder, textarea:-moz-placeholder {
      color: #636363;
    }
    
    链接地址: http://www.djcxy.com/p/194.html

    上一篇: 如何有效地从一堆袜子中配对?

    下一篇: 使用CSS更改HTML5输入的占位符颜色