How to make only placeholder italics in input

HtmlInputPlaceholder

Html Problem Overview


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?

Html Solutions


Solution 1 - Html

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.

Solution 2 - Html

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.

Solution 3 - Html

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionprabin badyakarView Question on Stackoverflow
Solution 1 - HtmlJoseph MarikleView Answer on Stackoverflow
Solution 2 - HtmlZacView Answer on Stackoverflow
Solution 3 - HtmlMike AronView Answer on Stackoverflow