askvity

How Do You Add Multiple Colors to Text in HTML?

Published in HTML Styling 2 mins read

You can add multiple colors to text in HTML by wrapping individual characters, words, or phrases within <font> tags (though <font> is deprecated, and using CSS is the recommended approach) or using <span> tags styled with CSS, and assigning different color values to each.

Here's a breakdown of the methods:

1. Using the Deprecated <font> Tag

While not recommended for modern web development due to its deprecation in favor of CSS, the <font> tag can achieve this.

Example:

<font color="red">H</font><font color="green">e</font><font color="blue">l</font><font color="orange">l</font><font color="purple">o</font>

This would render "Hello" with each letter in a different color.

2. Using <span> Tags and Inline CSS

A better, more modern approach is to use <span> tags combined with inline CSS styles. This provides more control and is the preferred method.

Example:

<span style="color: red;">H</span><span style="color: green;">e</span><span style="color: blue;">l</span><span style="color: orange;">l</span><span style="color: purple;">o</span>

This achieves the same result as the <font> tag example, but leverages CSS for styling.

3. Using <span> Tags and CSS Classes

For greater maintainability, you can define CSS classes and apply them to <span> tags.

Example (HTML):

<span class="red">H</span><span class="green">e</span><span class="blue">l</span><span class="orange">l</span><span class="purple">o</span>

Example (CSS - within <style> tags in the <head> or in a separate CSS file):

.red { color: red; }
.green { color: green; }
.blue { color: blue; }
.orange { color: orange; }
.purple { color: purple; }

This approach separates the styling from the content, making your code cleaner and easier to update.

4. Styling Words or Phrases

You can apply colors to entire words or phrases using the same methods described above. Simply wrap the desired text within the <font> or <span> tags.

Example (using <span> and CSS):

<span style="color: red;">This </span><span style="color: blue;">is </span><span style="color: green;">colorful text.</span>

Recommendation:

Using <span> tags with CSS (either inline or with classes) is the recommended approach for adding multiple colors to text in HTML. This adheres to modern web development best practices and allows for more flexible and maintainable styling. Avoid using the <font> tag as it is deprecated.

Related Articles