Josh Leitzel Josh Leitzel - 6 months ago 24
CSS Question

Is there a way to style part of an input field's value?

I'm working with an

field and I'd like to style part of the field as the user's typing in a different color. For example, let's say the
has a style declaration of
color: red;
and I want to change part of it to
color: blue;
. Is there any way this is possible?

If there isn't (as I suspect), any creative ideas on how I can simulate this effect while still preserving semantic mark-up?


Your suspicions are correct: styles will apply to the whole input only.

As styles can apply to the entirety of an element only, a solution will require at least one element per required colour.

Consider the division of the input field with respect to the point at which the user is making changes. There are three sections of the input:

  • that before the point at which changes are being applied
  • that after the point at which changes are being applied
  • that at the point the changes are being applied

You cannot achieve this with a single input element. And as the point at which the changes are being applied can change, the portions of the 'input' wrapped by the three elements will also change. JavaScript is required for a solution.

You should initially include a regular input element and forgo any of the required colouring. Use JavaScript to replace the input with a suitable container element. This can be styled to mimic an input element.

As changes occur, use JavaScript to identify the above-mentioned three divisions. Wrap them in suitable elements (spans would be ideal) and colour as needed.

Consider the following starting point for the generated replacement markup:

<div class="input">
  <span class="nonEdited before">foo</span>
  <span class="edited">fizz</span>
  <span class="nonEdited after">bar</span>

Use click, keydown and keyup events to figure out the three divisions for the input and to apply wrap the three portions of the faked input as required.