Using Colors in CSS


Using Colors in CSS

Colors in CSS can be applied to various elements like text, backgrounds, borders, and more. CSS provides multiple ways to specify colors, offering flexibility in how you style your elements.

1. Named Colors

  • CSS includes 140 predefined color names, such as red, blue, green, black, white, etc.

    p { color: blue; }

2. HEX Color Codes

  • HEX codes are represented by a # followed by 3 or 6 hexadecimal digits. The digits represent the intensity of red, green, and blue (RGB) on a scale from 00 to FF.

    h1 { color: #ff5733; /* R: FF, G: 57, B: 33 */ }

3. RGB Color Values

  • The rgb() function specifies a color using the red, green, and blue components, with each value ranging from 0 to 255.

    div { background-color: rgb(255, 99, 71); /* Tomato */ }

4. RGBA Color Values

  • The rgba() function is similar to rgb() but includes an alpha (transparency) component, where 1 is fully opaque and 0 is fully transparent.

    div { background-color: rgba(255, 99, 71, 0.5); /* Semi-transparent tomato */ }

5. HSL Color Values

  • The hsl() function stands for hue, saturation, and lightness. Hue is a degree on the color wheel (0-360), saturation is a percentage (0% means a shade of gray, 100% is full color), and lightness is also a percentage (0% is black, 100% is white).

    p { color: hsl(120, 100%, 50%); /* Bright green */ }

6. HSLA Color Values

  • The hsla() function adds an alpha channel to the hsl() model, defining transparency in the same way as rgba().

    p { color: hsla(120, 100%, 50%, 0.3); /* Semi-transparent green */ }

7. CurrentColor Keyword

  • The currentColor keyword can be used to apply the current text color (defined by color) to other properties, such as border-color.

    div { border: 2px solid currentColor; }

8. Gradients

  • CSS gradients allow you to create a smooth transition between two or more colors. They can be used as background images.
    • Linear Gradient:

      background: linear-gradient(to right, red, yellow);
    • Radial Gradient:

      background: radial-gradient(circle, red, yellow);

Applying Colors to Various Properties

  • Text Color:

    p { color: #333; }
  • Background Color:

    body { background-color: #f0f0f0; }
  • Border Color:

    div { border: 2px solid #000; }

Example Usage

body { background-color: #fafafa; } h1 { color: #ff4500; } p { color: hsl(210, 100%, 40%); background-color: rgba(0, 128, 0, 0.1); border: 2px solid currentColor; }