RGB Color Model in JavaScript
The color attribute of CSS represents the color of the element, which can be defined using various ways like RGB
, HSL
, LCH
, HWB
, Color keyword
, etc. You can read more about what these various ways of representing color mean here: https://en.wikipedia.org/wiki/Color_theory.
RGB
is a popular color model which is supported by all browsers. RGB stands for red, blue, and green, also known as primary colors. Various proportions of these primary colors will produce many more color shades.
RGB
cubic model represents red color on X
axis, green color on Y
axis, and blue color on Z
axis. If all the three coordinates meet at 0
, that represents the black
color, and 255
represents the white
color.
RGB
colors can be defined in two ways, the functional way and the hexadecimal way.
Functional notation accepts Arithmetic
, Percentage
, Digital 8-bit per channel
, Digital 12-bit per channel
, Digital 16-bit per channel
, and Digital 24-bit per channel
color format. Hexadecimal notation can be defined in two ways, either using 6 digits or 3 digits.
Syntax of rgb()
Color in JavaScript
rgb($red, $green, $blue);
rgba($red, $green, $blue, $alpha);
#RRGGBB[AA]
#RGB[A]
Parameter of rgb()
Color in JavaScript
$red
: It is a mandatory parameter that defines the intensity of red shed in the final color. Its range is0-255
in functional and0-9, A-F
in hexadecimal notation.$green
: It is a mandatory parameter that defines the intensity of green shed in the final color. Its range is0-255
in functional and0-9, A-F
in hexadecimal notation.$blue
: It is a mandatory parameter that defines the intensity of blue shed in the final color. Its range is0-255
in functional and0-9, A-F
in hexadecimal notation.$alpha
: It is an optional parameter that defines the transparency of the color. It takes value in percentage, float value.
Example Code:
<div id="demo">
<h1>Hello world!</h1>
<p>Welcome to RGB tutorial</p>
</div>
div {
color: rgb(12, 45, 255, 0.7);
padding: 20px;
}
<script>
const tag = document.getElementById("demo");
tag.style.color = "rgb(255, 45, 255, 0.7)";
</script>
Output:
Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.
LinkedIn