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
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+.
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>';
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With