CSS Colors

Why Colors Matter

Colors help make websites visually appealing and functional. They enhance readability, draw attention to important elements, and support a site’s branding and accessibility.

For example, error messages are often red, while success messages are green.

Color Property in CSS

The color property sets the text color, and the background-color property sets the background of an element.

Example Using Inline Styling

Here’s a live inline HTML example:

<p style="color: blue; background-color: lightyellow;">
        This paragraph has blue text on a green background.
        </p>
This paragraph has blue text on a green background.

Color Values

CSS supports multiple formats for defining colors:

  • Named colors: red, blue, green
  • Hexadecimal: #ff0000 (Red)
  • RGB: rgb(255, 0, 0)
  • RGBA: rgba(255, 0, 0, 0.5) (with transparency)
  • HSL: hsl(0, 100%, 50%)
  • HSLA: hsla(0, 100%, 50%, 0.3)

Background vs Text Colors

Use color to style the text and background-color to color the background of elements.

h1 {
  color: white;
  background-color: #333333;
}

Using Transparency

RGBA and HSLA formats allow transparency by adjusting the alpha channel (last value):

  • 0 = fully transparent
  • 1 = fully opaque
div {
  background-color: rgba(0, 0, 255, 0.3);
}

Practice Prompt

Create a styled box with the following:

  • A red background using a named color
  • White text using a hex code
  • A paragraph inside with a semi-transparent blue background using RGBA
<div style="background-color: red; color: #ffffff; padding: 20px;">
  <p style="background-color: rgba(0, 0, 255, 0.5);">
    This is a semi-transparent paragraph inside a red box.
  </p>
</div>

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic