Skip to main content

How to Change the Text Color in CSS

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

The color property sets the color of text. Set it on body and the whole page follows, then give a single element its own color where it should stand out.

Syntax​

Syntax
<selector> {
color: <color>;
}
PartWhat it does
<selector>The elements whose text to color, such as body or h1.
<color>The color: a hex code such as #616161, a name such as teal, or an rgb() value.

MDN's color page lists every way to write the value.

The Example​

The example is a welcome page with a heading and one paragraph. One rule makes the page's text dark grey, and another makes the heading blue.

Step 1: Write the Code​

Create a file named index.html in a text editor, such as Visual Studio Code:

index.html, an HTML page with a style element holding a rule for body that sets the color 616161 and a rule for h1 that sets the color 0f6cbd, and a body with the heading Welcome and one paragraph.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Text color</title>
<style>
body {
color: #616161;
}

h1 {
color: #0f6cbd;
}
</style>
</head>
<body>
<h1>Welcome</h1>
<p>The office opens at 9:00.</p>
</body>
</html>

Step 2: Open It in a Browser​

Double-click index.html. It opens in your browser:

The page in Chromium: the heading Welcome in blue and the paragraph The office opens at 9:00. in grey.

The screenshot comes from Chromium 159, the open-source browser that Chrome is built on.

What Happened​

  • The paragraph is grey, although no rule names p. It inherited the color of body, rgb(97, 97, 97), which is #616161. Text color passes down to the elements inside.
  • The heading is blue, rgb(15, 108, 189). Its own rule wins over the color it would inherit from body.

Common Mistakes​

MistakeWhat happensDo this instead
The British spelling: colourIt isn't a CSS property, so Chromium ignored it and the text stayed blackWrite color
Leaving out the #: color: 0f6cbdThe value is invalid and ignored: the text stayed blackWrite #0f6cbd

Troubleshooting​

SymptomLikely causeFix
The text stays blackThe property or the value is misspelledCheck color and the #
One element ignores the page colorIt has its own color ruleRemove that rule, or change it

FAQ​

Can I use color names?​

Yes. color: teal gave rgb(0, 128, 128). MDN's named-color page lists every name.

Can I write the color with rgb()?​

Yes. color: rgb(0 131 143), with spaces between the numbers, worked and gave rgb(0, 131, 143).

Conclusion​

Set color on body for the page's text, and on any element that needs its own color. Spell it the American way, and start hex codes with #.

Additional Resources​