Setting the text colour of an HTML element using CSS involves using the color
property. It allows you to define the colour of the text content within the selected element.
Note: The color
property can take various colour values, such as named colours, hexadecimal, RGB, or HSL values.
Syntax:
p {
color: #336699;
}
h1 {
color: red;
}
The text color will be changed using the following methods :
-
Class Selector: Assign the same text colour to multiple elements by defining a CSS class (e.g
.custom-text-color
) and applying it using theclass
attribute. -
ID Selector: Set a unique text colour for a specific element using an ID selector (e.g.,
#geeks
), ensuring individualized styling on the page. -
Inline Style: Customize the colour of a single element swiftly by adding an inline style (e.g.,
style="color: #2ecc71;"
) directly within the HTML tag.
Example:
HTML
<!DOCTYPE html> < html lang = "en" >
< head >
< title >Color the Text</ title >
< style >
.custom-text-color {
color: #3498db;
}
#geeks {
color: red;
}
</ style >
</ head >
< body >
< p class = "custom-text-color" >
This text will be colored using class
</ p >
< span id = "geeks" >
This text will be colored using id
</ span >
< p style = "color: #2ecc71;" >
This text is coloured using inline CSS.
</ p >
</ body >
</ html >
|
Output:
Features
-
Color Values: Accepts a wide range of color values, including keywords (e.g.,
red
,blue
), hexadecimal codes (e.g.,#336699
), RGB, or HSL values. - Inheritance: Text color can be inherited from parent elements, affecting the entire document or specific sections.
- Selectors: Can be applied to various HTML elements using different selectors (e.g., element selectors, class selectors, ID selectors).