Using RGB for Color Values
CSS uses two functions to express color properties using RGB. The first function is rgb
and the second rgba
.
Both functions have three input values. One for red, one for green and one for blue. These use the number range of 0 to 255.
The rgb
function syntax
Examples of the rgb
function
-
rgb(0,0,0)
black -
rgb(255,255,255)
white -
rgb(255,0,0)
red -
rgb(0,255,0)
green -
rgb(0,0,255)
blue -
rgb(255,0,255)
magenta -
rgb(0,255,255)
cyan -
rgb(255,255,0)
yellow -
rgb(255,215,0)
gold -
rgb(192,192,192)
silver
The rgba
function syntax
The rgba
has one additional value to express opacity which is called alpha or the alpha channel. It is a decimal value from 0 to 1.
The rgba
is more likely used against a container's background color or a container's background image.
Examples of the rgba
function
-
rgba(0,0,0,1)
black 100% opaque. -
rgba(0,0,0,.5)
black 50% opaque. -
rgba(255,255,255,1)
white 100% opaque. -
rgba(255,255,255,.75)
white 75% opaque. -
rgb(255,0,0,1)
red 100% opaque. -
rgb(255,0,0,.25)
red 25% opaque. -
rgb(0,0,255,1)
blue 100% opaque. -
rgba(0,0,255,.25)
blue 25% opaque. -
rgb(0,0,255,0)
blue 0% opaque.
Activity:
Objective: To replace hex color values with the rgb
function.
Setup:
Copy all the files from the start-03 folder to practice folder and replace if necessary.
The activity's completed file can be found in the completed folder.
Steps:
-
Open the color-rgb.html file in your web browser.
-
Open the color-rgb.css file in your code editor. It has the following contents:
@charset "UTF-8"; body{ background-color:#008080; color:#fff; } h1, h2, h3, h4, h5, h6{ background-color:#ff6347;/*tomato*/ color:#000; } p{ background-color:#000; }
All these properties are using hex color values.
-
DIY: Replace all the hex values in the color-rgb.css with
rgb
function for same colors.HINT: Use a color picker tool to help make the conversions. For example Color Minder.
@charset "UTF-8"; body{ background-color:rgb(0,128,128); color:rgb(255,255,255); } h1, h2, h3, h4, h5, h6{ background-color:rgb(255,99,71);/*tomato*/ color:rgb(0,0,0); } p{ background-color:rgb(0,0,0); }
The changes are shown in bold.
-
DIY: Validate the color-rgb.css file at W3C CSS Validation service.