Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html Color only (*) symbol in input placeholder field in form

I have the following code:

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

How can I color the (*) symbol in the placeholder value red without coloring the other text with it (being First Name text)?

Any help is much appreciated!

Thank you! Al

like image 716
Baraa Avatar asked Apr 17 '15 23:04

Baraa


2 Answers

One possible option could be using :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 ::before/::after pseudo-elements over the 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's worth noting that :valid pseudo-class is supported in IE10+.

like image 73
Hashem Qolami Avatar answered Sep 18 '22 15:09

Hashem Qolami


Unfortunately, it isn't possible to change the color of certain text in a input :( you can try to use a contenteditable div:

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

Then, you have to add and remove the placeholder with JS:

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

JSFiddle Demo

like image 33
Jacob Gray Avatar answered Sep 21 '22 15:09

Jacob Gray