Change color of one character in a text box HTML/CSS

103,897

Solution 1

You can't do this with a regular <input type="text"> or <textarea> element, but with a normal element (like <div> or <p>) made contenteditable, you have all the freedoms of html/css formatting.

<div contenteditable>
    ST<span style="color: red">A</span>CK OVERFLOW
</div>

http://jsfiddle.net/jVqDJ/

The browser support is very good as well (IE5.5+). Read more at https://developer.mozilla.org/en-US/docs/Web/HTML/Content_Editable

Solution 2

I just want to add to the solution if you want to change color of only first character then there is a CSS selector element::first-letter

example:

div::first-letter{
   color: red;
}

Solution 3

I can't believe no one has suggested this yet. But if you're ok with a WebKit only solution, you can make a color gradient with discrete separations and apply it to the text like this:

.c1 {
  background: linear-gradient(to right, black 0% 1.19em, red 1.19em 1.9em, black 1.9em 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.c2 {
  color: white;
  background: linear-gradient(to right, black 0% 1.19em, red 1.19em 1.9em, black 1.9em 100%);
  
}

input{
  font-family: "Courier New", Courier;
}

.c3 {
  background: linear-gradient(to right, black 0% 1.4em, red 1.2em 1.95em, black 1.95em 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
<h1 class="c1">
STACK OVER FLOW
</h1>
This is what the gradient looks like with the text over it:
<h1 class="c2">
STACK OVER FLOW
</h1>
It even works on input forms, however you'll want to change the font to a Monospaced font like Courier so the color always lines up with the same letter:
<h1>
<input type="text" class="c3"></input>
</h1>

This is nice because it's not limited by the tag the text is placed in like some of the other answers. And if you're in a situation where you can't really change the html (for instance if you're using the same style sheet on multiple pages and need to make a retroactive change) this could be helpful. If you can change the html though, xec's answer has much better browser support.

Share:
103,897
bluewonder
Author by

bluewonder

Updated on January 16, 2022

Comments

  • bluewonder
    bluewonder over 2 years

    I'm designing a web site and i would like to ask you guys that, how can I change the color of just one character in a string in a text box of HTML by CSS?

    example : STACK OVER FLOW just the 'A' letter is red!