0
0
CssHow-ToBeginner · 3 min read

How to Use RGB Color in CSS: Simple Syntax and Examples

In CSS, you use the rgb() function to set colors by specifying red, green, and blue values from 0 to 255. For example, color: rgb(255, 0, 0); sets the color to bright red.
📐

Syntax

The rgb() function takes three numbers representing the intensity of red, green, and blue colors. Each number ranges from 0 (none) to 255 (full intensity). The format is rgb(red, green, blue).

  • red: Number from 0 to 255 for red intensity
  • green: Number from 0 to 255 for green intensity
  • blue: Number from 0 to 255 for blue intensity
css
selector {
  color: rgb(255, 0, 0); /* bright red */
}
💻

Example

This example shows how to set the background color of a webpage to a soft blue using rgb(). It demonstrates how the three values combine to create the final color.

css
html {
  height: 100%;
  margin: 0;
}
body {
  background-color: rgb(100, 149, 237); /* cornflower blue */
  color: white;
  font-family: Arial, sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
}
p {
  font-size: 2rem;
}
Output
A full browser window with a cornflower blue background and centered white text that says: "This background uses rgb(100, 149, 237)"
⚠️

Common Pitfalls

Common mistakes when using rgb() include:

  • Using values outside the 0-255 range, which will be ignored or cause unexpected colors.
  • Forgetting commas between the numbers.
  • Using percentages without the rgb% syntax (which is different).

Always use commas and numbers between 0 and 255.

css
/* Wrong: missing commas and out of range values */
selector {
  color: rgb(300, 0, 0); /* wrong: 300 is too high */
}

/* Correct: commas and valid values */
selector {
  color: rgb(255, 0, 0); /* bright red */
}
📊

Quick Reference

PropertyExampleDescription
colorcolor: rgb(0, 128, 0);Sets text color to medium green
background-colorbackground-color: rgb(255, 255, 0);Sets background to bright yellow
border-colorborder-color: rgb(0, 0, 255);Sets border color to blue

Key Takeaways

Use the rgb() function with three numbers from 0 to 255 to set colors in CSS.
Separate red, green, and blue values with commas inside rgb().
Values outside 0-255 or missing commas cause errors or unexpected colors.
rgb() works for any CSS property that accepts colors like color, background-color, and border-color.
Test colors in a browser to see how the RGB values combine visually.