I have the following code:
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>';
});
});
You probably can't, like that. The best way to do this would be something like this SO answer: Multiple font colors in an Input tag
In essence, a second div is put over the input field, allowing for the change in colour.