In this tutorial, we aim to understand the various color formats available in CSS (Cascading Style Sheets). This is an essential skill for any web developer as colors play a vital role in a website's aesthetics.
You will learn how to:
Prerequisites: Basic understanding of HTML and CSS is required.
CSS offers several methods to represent color:
Hexadecimal color codes start with a hash symbol (#), followed by six digits and/or letters. The first two characters represent the red color, the middle two are for green, and the last two are for blue.
Example: #RRGGBB
RGB stands for Red, Green, Blue. It is represented as rgb(red, green, blue)
, each value can range from 0 to 255.
Example: rgb(255,255,255)
RGBA is similar to RGB but includes an alpha channel that specifies the opacity. The alpha value ranges from 0 (transparent) to 1 (fully opaque).
Example: rgba(255,255,255,0.5)
HSL stands for Hue, Saturation, Lightness. Hue ranges from 0 to 360 (representing degrees on a color wheel), while Saturation and Lightness are represented as percentages.
Example: hsl(120, 100%, 50%)
HSLA is similar to HSL but includes an alpha channel that specifies the opacity.
Example: hsla(120, 100%, 50%, 0.3)
body {
/* This sets the body background color to red */
background-color: #FF0000;
}
body {
/* This sets the body background color to green */
background-color: rgb(0,128,0);
}
body {
/* This sets the body background color to blue with 50% opacity */
background-color: rgba(0,0,255,0.5);
}
body {
/* This sets the body background color to yellow */
background-color: hsl(60, 100%, 50%);
}
body {
/* This sets the body background color to pink with 30% opacity */
background-color: hsla(330, 100%, 50%, 0.3);
}
We've covered various CSS color formats - Hexadecimal, RGB, RGBA, HSL, and HSLA. Each of these formats has its own use-cases and benefits.
Next, you might want to learn about the currentColor
keyword in CSS or CSS Variables.
Additional Resources:
Solutions:
p { background-color: rgba(0, 0, 0, 0.5); }
This sets the paragraph background to black with 50% opacity.
h1 { color: hsl(39, 100%, 50%); }
This sets the heading color to orange.
a { color: hsla(270, 100%, 50%, 0.5); }
This sets the link color to purple with 50% opacity.
Tips for further practice: Try to create a color palette for a website using different CSS color formats.