askvity

How to Write RGB Color Code in HTML?

Published in HTML & CSS 3 mins read

You can write RGB color codes in HTML using the rgb() function within the style attribute or in CSS stylesheets. The rgb() function takes three values representing the intensity of red, green, and blue, each ranging from 0 to 255.

Here's a breakdown of how to use RGB color codes effectively:

Inline Styling (Using the style attribute)

You can apply RGB colors directly to HTML elements using the style attribute.

<p style="color:rgb(255, 0, 0);">This text is red.</p>
<div style="background-color:rgb(0, 255, 0);">This div has a green background.</div>
<h1 style="color:rgb(0, 0, 255);">This heading is blue.</h1>

In these examples:

  • color:rgb(255, 0, 0); sets the text color to red (red is at full intensity, green and blue are off).
  • background-color:rgb(0, 255, 0); sets the background color to green (green is at full intensity, red and blue are off).
  • color:rgb(0, 0, 255); sets the text color to blue (blue is at full intensity, red and green are off).

Internal or External CSS

You can also define RGB colors in your CSS stylesheets (either within <style> tags in the HTML document or in separate .css files).

<!DOCTYPE html>
<html>
<head>
<style>
  body {
    background-color: rgb(240, 240, 240); /* Light gray background */
  }

  h1 {
    color: rgb(50, 50, 50); /* Dark gray heading */
  }

  p {
    color: rgb(100, 100, 100); /* Medium gray paragraph text */
  }
</style>
</head>
<body>

<h1>My Heading</h1>
<p>Some text here.</p>

</body>
</html>

Or, in an external CSS file (style.css):

body {
  background-color: rgb(240, 240, 240);
}

h1 {
  color: rgb(50, 50, 50);
}

p {
  color: rgb(100, 100, 100);
}

Then, link the CSS file in your HTML:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="style.css">
</head>
<body>

<h1>My Heading</h1>
<p>Some text here.</p>

</body>
</html>

Common RGB Color Values:

Here's a small table for some commonly used RGB colors:

Color RGB Value
Red rgb(255, 0, 0)
Green rgb(0, 255, 0)
Blue rgb(0, 0, 255)
White rgb(255, 255, 255)
Black rgb(0, 0, 0)
Gray rgb(128, 128, 128)
LightGray rgb(211,211,211)

RGB with Opacity (RGBA)

HTML and CSS also support rgba(), which allows you to specify the opacity (transparency) of the color. The 'a' stands for alpha. The fourth value in the rgba() function is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

.transparent-box {
  background-color: rgba(255, 0, 0, 0.5); /* Semi-transparent red */
  color: white;
  padding: 10px;
}
<div class="transparent-box">
  This is a semi-transparent box.
</div>

Writing RGB color codes in HTML involves using the rgb() function within the style attribute or within CSS, providing values for red, green, and blue intensities (0-255), or using rgba() to also specify opacity.

Related Articles