Working with Colors and Backgrounds

Discover how to use CSS to control text color, background color, and background images. Learn about different color models (hex, RGB, HSL).


CSS Colors and Backgrounds

Working with Colors in CSS

Colors are fundamental to web design. CSS offers various ways to define and apply colors to elements, allowing you to create visually appealing and engaging web pages.

Controlling Text Color

The color property in CSS is used to set the text color of an element.

This text is styled using the color property.

 .text-color-example {
                color: #007bff; /* Example color: a shade of blue */
            } 

Controlling Background Color

The background-color property sets the background color of an element.

This element has a background color applied.
 .background-color-example {
                background-color: #f0f8ff; /* Example color: AliceBlue */
            } 

Using Background Images

The background-image property allows you to set an image as the background of an element. You can further control the appearance with properties like background-repeat, background-size, and background-position.

Background Image Example
 .background-image-example {
                background-image: url('image.jpg'); /* Replace with your image URL */
                background-repeat: no-repeat;
                background-size: cover; /* or contain, or specific dimensions */
                color: white; /* Ensure text is readable on the image */
                text-align: center;
                padding: 50px;
            } 

Color Models: Hex, RGB, and HSL

CSS supports different color models. Here's a brief overview:

Hexadecimal (Hex)

Hex codes are six-digit values that represent colors. The first two digits represent red, the next two represent green, and the last two represent blue. Each pair ranges from 00 to FF (0 to 255 in decimal). They are prefixed with a #.

This text is red, defined using a hex code.

 .hex-color-example {
                color: #ff0000; /* Red */
            } 

RGB (Red, Green, Blue)

RGB values specify the intensity of red, green, and blue light. Each value ranges from 0 to 255. The syntax is rgb(red, green, blue).

This text is green, defined using RGB values.

 .rgb-color-example {
                color: rgb(0, 255, 0); /* Green */
            } 

HSL (Hue, Saturation, Lightness)

HSL represents colors using hue (the color's position on the color wheel, in degrees), saturation (the color's purity, as a percentage), and lightness (the color's brightness, as a percentage). The syntax is hsl(hue, saturation, lightness).

This text is blue, defined using HSL values.

 .hsl-color-example {
                color: hsl(240, 100%, 50%); /* Blue */
            }