66

How can I format the text of a placeholder in italics, but when someone writes inside the textbox, the text shouldn't be in italics.

code:

<input type="text" id="search" placeholder="Search" style="font-style:italic">

How can I place italic text only on placeholder but not whole input?

3 Answers 3

113

Sure. Just apply the style to these CSS rules:

::-webkit-input-placeholder {
   font-style: italic;
}
:-moz-placeholder {
   font-style: italic;  
}
::-moz-placeholder {
   font-style: italic;  
}
:-ms-input-placeholder {  
   font-style: italic; 
}

Probably not all of these rules are needed. I always just reference CSS Tricks because I always forget how to do it.

Edit: Note that these rules cannot be combined into one selector. They must be declared separately as noted by Dave Kennedy in the comments below.

3
  • 9
    Unfortunately it seems that these rules have to be declared separately, i.e. ::-webkit-input-placeholder, ::-moz-placeholder { font-style: italic; } doesn't work. Dec 21, 2016 at 18:13
  • 1
    @DaveKennedy Yes, you are correct. I noticed that too. I'm not sure why that is the case, however. Dec 21, 2016 at 18:23
  • 16
    @DaveKennedy @JosephMarikle It's part of the CSS3 Spec. Specifically: a group of selectors containing an invalid selector is invalid. Therefore, because Firefox sees :-ms-input-placeholder as invalid, it makes the whole selector group as invalid. That's why you need to keep them separate.
    – luc122c
    Nov 6, 2017 at 13:59
33

From MDN, you can use the :placeholder-shown pseudo-class.

input:placeholder-shown {
   font-style: italic;
}

This has the advantage of being un-prefixed, and the browser support is decent (92-ish%) at the time of this writing: https://caniuse.com/#feat=css-placeholder-shown.

4

Another way: the :focus selector is your friend. To make it only for the placeholder use the :not selector. This have the CSS rule only if the input field is NOT current selection. Define in your CSS :

.class-of-your-input-field:not(:focus) {
font-style:italic;
}
2
  • Wouldn't this also make regular input text italic in addition to making placeholder text italic?
    – Kevin
    Jun 20, 2019 at 21:15
  • 3
    This has the unfortunate effect that once the empty input box gets focus, it will lose the italic, while still having the placeholder.
    – Gru
    Jan 17, 2020 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.