Adding Colors and Backgrounds in HTML
Colors and backgrounds are essential for creating visually appealing web pages. In this lesson, we will learn how to use HTML and CSS to add colors to text, set background colors, and even use images as backgrounds.
Text Color
You can change the color of text using the `style` attribute and the `color` property:
<p style="color: blue;">This text is blue.</p>
This changes the color of the text to blue. You can use color names, hexadecimal values (e.g., `#0000FF`), RGB values (e.g., `rgb(0, 0, 255)`), or HSL values.
Background Color
To change the background color of an element, use the `background-color` property:
<div style="background-color: lightgray;">
<p>This is a paragraph with a light gray background.</p>
</div>
This will give the `div` element a light gray background. You can apply this to most HTML elements, including the entire page.
Background Images
You can also set an image as the background of an element using the `background-image` property:
<div style="background-image: url('background.jpg');">
<p>This is a paragraph with a background image.</p>
</div>
Make sure the image path is correct. Background images are often used in combination with background colors for a layered effect.
Using External CSS
Although we have been using inline styles, it's recommended to use an external CSS file for managing styles, especially for larger projects. Here’s an example of how you can apply styles using an external CSS file:
/* styles.css */
body {
background-color: #f0f0f0;
color: #333;
}
h1 {
color: #4CAF50;
}
p {
background-color: #e9ecef;
padding: 10px;
border-radius: 5px;
}
This example changes the background color of the entire page, sets a color for headings, and styles paragraphs with a light gray background, padding, and rounded corners.
Practice Exercise
Try experimenting with different text colors, background colors, and background images on your webpage. You can also explore the various ways to specify colors (hex, RGB, HSL) and observe the effects.
Proceed to Lesson 7