Html Color only (*) character in the placeholder input field in the form

I have the following code:

<input id="firstName" name="fname" type="text" maxlength="50" placeholder="First Name *" required> 

How can I color the character (*) in the placeholder value in red without coloring another text with it (which is the name)?

Any help is much appreciated!

Thanks! Al

+6
source share
3 answers

Unfortunately, it is not possible to change the color of certain text in the input file :( you can try using a contenteditable div:

 <div class="input" contenteditable>First Name <span style="color:red;">*</span></div> 

Then you need to add and remove the placeholder using JS:

 $(function(){ $('.input').focus(function(){ $(this).html(''); }); $('.input').blur(function(){ if($(this).html()=='') this.innerHTML='First Name <span style="color:red;">*</span>'; }); }); 

JSFiddle Demo

+3
source

One possible option would be to use :valid pseudo-class for the required <input> to make the Absolutely Positioned sibling element disappear - which is used as a placeholder under the input.

So, we can use the ::before / ::after pseudo-elements over an absolutely positioned element to change the color of our pseudo-placeholder.

 .input-wrapper { display: inline-block; position: relative; } .input-wrapper input { background: transparent; border: 1px solid #999; } .input-wrapper input:valid + .placeholder { display: none; } .input-wrapper .placeholder { position: absolute; top: 1px; left: 2px; z-index: -1; } .input-wrapper .placeholder::before { content: attr(data-placeholder); color: #999; } .input-wrapper .placeholder::after { content: " *"; color: tomato; } 
 <div class="input-wrapper"> <input id="firstName" name="fname" type="text" maxlength="50" required> <span class="placeholder" data-placeholder="First Name"></span> </div> 

It is worth noting that IE10 + supports the pseudo-class :valid .

+5
source

You probably won't be able to. The best way to do this is with something like this SO answer: Several font colors in the input tag

In fact, the second div is placed over the input field, which allows you to change the color.

0
source

Source: https://habr.com/ru/post/985387/


All Articles