CSS Text Formatting
CSS has many properties for styling and formatting text, such as the text color, alignment, spacing, decoration, and transformation.
CSS Text Color
The color property sets the color of the text.
The color can be a name (like red), a HEX value (like #ff0000), or an RGB value (like rgb(255,0,0)).
The default text color for a page is set in the body selector.
Example
The body text is blue, the <h1> is green, and the <h2> is red.
Prompt
An HTML page that sets text colors with the color property in an internal style block.
Make the body text blue, the
<h1> green, and the <h2> red. Add a heading of each level and a paragraph.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
color: blue;
}
h1 {
color: green;
}
h2 {
color: red;
}
</style>
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<p>This is an ordinary paragraph. The body text color is blue.</p>
</body>
</html>
Text Color and Background Color
You can set both the background-color and the color of an element.
Important: High contrast matters for people with vision problems, so always keep good contrast between the text color and the background.
Example
The body, heading, and div each pair a background color with a text color.
Prompt
An HTML page that sets both background color and text color together.
In an internal
<style> block, give the body a lightgrey background and blue text, the <h1> a black background and white text, and a <div> a blue background and white text. Add a heading, a div with text, and a paragraph.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
background-color: lightgrey;
color: blue;
}
h1 {
background-color: black;
color: white;
}
div {
background-color: blue;
color: white;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<div>This is a div with a blue background and white text.</div>
<p>This is a paragraph. The body text is blue on a light grey background.</p>
</body>
</html>