Styling part of the text in the placeholder

前端 未结 2 1393
后悔当初
后悔当初 2020-12-12 02:50

I would like to modify the css style of a part of placeholder. Attention not all the placeholder.

If my placeholder is: \"Wher

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 03:45

    Yes (ish)... but I wouldn't recommend it.

    In some browsers you can use the :before pseudo element on the placeholder and style that separately but you'll have to make the 'Search' prefix part of the pseudo element rather than in the actual placeholder attribute:

    ::-webkit-input-placeholder {
       color: #ABABAB;
       font-style: italic;
    }
    :-moz-placeholder { /* Firefox 18- */
       color: #ABABAB;
       font-style: italic;
    }
    ::-moz-placeholder {  /* Firefox 19+ */
       color: #ABABAB;
       font-style: italic;
    }
    :-ms-input-placeholder {  
       color: #ABABAB;
       font-style: italic;
    }
    /* prepend the 'Search' prefix */
    ::-webkit-input-placeholder:before {
        content: "Search ";
        font-style: normal;  
    }
    :-moz-placeholder:before {
        content: "Search ";
        font-style: normal;  
    }
    ::-moz-placeholder:before {
        content: "Search ";
        font-style: normal;  
    }
    :-ms-input-placeholder:before {
        content: "Search ";
        font-style: normal;  
    }

    Works for me in Chrome but your mileage may vary. I've added the vendor-prefixes just in case but I've not tested it in anything else. As noted in the comments - it doesn't work in Firefox, and probably shouldn't work anywhere! Furthermore, it is considered bad-form to style the placeholders this way as they are not really presentational elements but just kind of helpers to inform users of what's expected.

    A better solution would be to NOT style the placeholders at all aside from giving them a font/colour to suit your theme.

    See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-placeholder.

    A good form will use label, placeholder and title in combination to clearly describe the expected input. Modern browsers will also use the title attribute's value in the required field dialogue when you try to submit an invalid required field. Try this example:

提交回复
热议问题