How to change the color of text in html and css


In HTML, the text color is controlled by CSS, or cascading style sheets, which specifies all of the styles used in the HTML. Things like font size, font type, text color and text size are all controlled there.

In this tutorial, I will show you several methods to change the text color!

You can use this site which has a list of predefined color names https://www.w3schools.com/cssref/css_colors.php. Or, you can directly input a color hexadecimal (such as #ff00ff). You can also use the rgb(redvalue, greenvalue, bluevalue) or hsl(huevalue, saturationvalue, lightnessvalue) with decimal numbers (such as rgb(255, 0, 255)).


Method 1: Create a class in CSS

The first method is to create a custom class in CSS that will contain the color information. Notice the custom class is preceded by a dot. You can then use the class in any HTML tag by adding the class= field before the first >.

<style>
.myclass {
    color:red;
}
</style>

<p class=myclass>
Testing!
</p>


Method 2: Styles for HTML types

In HTML, there are multiple tags you can use: paragraph, body, headings etc. In CSS, you can define custom styles for any of these predefined tags, in the following way (notice there is no dot in front here):

<style>
p {
    color:red;
}
</style>
<p>
Testing!
</p>


Method 3: Inline styles

Another way is inline definition of styles, as shown in the example below. Instead of defining styles in the style tag, you directly define them inline under the style parameter.

<p style="color:red">
Testing!
</p>


Method 4: Using the id field

In CSS, the ids are always preceded by a # (hash key). You can then assign an id via the id field inside of the first tag, just like you did with class.

<style>
#myid {
        color:red;
}
</style>
<p id=myid>
Testing!
</p>


Method 5: Using a styles file

You can also put your CSS in an external file. Just create a stylename.css file. You can then link it in the head part of the code.

<head>
      <link rel="stylesheet" href="style.css">
</head>


Example:

A
B
C

<div style="color:red">A</div><div style="color:green">B</div><div style="color:blue">C</div>