Using Color in CSS

Using Color in CSS
1and1 placeholder image

So far we have seen how to apply the colors red, blue, and green, but there are many other ways to specify a color other than by their names.

Aren't colors pretty?
Aren't colors pretty?

Red, Green, Blue Value

This format is probably the easiest to understand because all you have to do is specify what proportion of each color you want.

You can either go percentage-based, meaning 0% for none and 100% for all, or you can go byte-based, meaning 0 is for none and 255 is for all.

For example, if you wanted full-blown blue as your page's background color, you would set red and green to 0, but leave the last value at max, like so:

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

Or if you wanted purple, you could specify half red and half blue, like so:

	
	body {
		background-color: rgb(50%, 0, 50%);
	}
	

Hexadecimal Value

Alternatively, you can use a color's hex value. To declare a hex value, you first start with a hash symbol, followed by six digits in base-16.

In base-16, the lowest digit is 0 and the highest is F, where each color is given two digits each. With hex values, if you wanted full-blown green, it would look like this:

	
	body {
		background-color: #00FF00;
	}
	

Hue, Saturation, Lightness Value

The final way to declare a color is to specify its hue, saturation and lightness. If you've ever used a color wheel:

A color wheel with colors for days.
A color wheel with colors for days.

You can think of the hue as the degree, 0 to 360, on that wheel. On the wheel, 0 degrees is red, 120 degrees is green and 240 degrees is blue.

The saturation is a percentage describing how much color there should be. 0% would be a shade of gray whereas 100% is the full color.

The lightness is another percentage describing how light or dark the color should be, with 0% being black and 100% being white.

Here is an example of light green:

	
	body {
		background-color: hsl(120, 100%, 75%);
	}
	

Alpha Transparency

CSS allows you to define colors that have an alpha, which basically means how transparent the color will be.

Red, Green, Blue, Alpha Value

Instead of three numbers defining how much red, green and blue is in the color, you now can use a fourth number to define the alpha, like so:

	
	p {
		background-color: rgba(255, 0, 255, 0.5);
	}
	

The alpha is a value between 0 (entirely opaque) and 1 (entirely transparent), so 0.5 is equivalent to 50%.

Hue, Saturation, Lightness, Alpha Value

Similarly to when you use RGBA, you can do the exact same with HSLA. Below is an example usage:

	
	p {
		background-color: hsla(25, 40%, 85%, 0.7);
	}
	

How cool is that? In our next lesson, we discuss how to work with fonts and text.

Resources