Color Values: How to Define a Color in CSS

Published September 19, 2016 by CSS Newbies.

There are many different scenarios in which you’d have to define a color in your CSS — this probably most commonly happens with the color or background-color property, but it’s certainly used with others as well. Defining your color values is the easy part, but deciding how to do so can sometimes be tricky, because there are so many different ways to define a color value using CSS. Here are all your options:

Predefined Name Values

Most people don’t use predefined name values to define color in their CSS because there are only about 140 predefined colors in the CSS lexicon — hardly enough to be creative in your designs.

h1{
color: green;
}

HEX Color Values

This one’s probably the most common of them all. It’s six (sometimes three, if all the characters are the same) characters (digits or letters) preceded by a # symbol, and is supported by all major browsers.

h1{
color: #00ff00; /* green */
}

RGB/RGBA Color Values

RGB colors are defined by the amounts of intensity of red, green, and blue in the color. The syntax is like this: rgb(red, green, blue). So each parameter within the parenthesis represents the intensity of each particular color.

RGBA is the same as rgb, except with an added “a” parameter, which stands for alpha. Alpha represents the opacity of a color, and can be a number value from 0-1. So if .5 is used as the “a” parameter, the color itself will be only partially opaque. This is used often when trying to make the background color of a particular object slightly transparent so the user can see behind it.

h1{
color:rgb(0, 255, 0); /* green */
}

h2{
color:rgba(0, 255, 0, 1); /* green */
}

HSL/HSLA Colors

HSL colors are defined by the amounts of hue, saturation, and lightness in a color. The syntax, much like RGB, is hsl(hue, saturation, lightness). Also like RGB, there is also an option to include an alpha value, which serves the save purpose as the alpha value does for rgba. The syntax for that is: hsla(hue, saturation, lightness, alpha).

h1{
color: hsl(120, 100%, 50%); /* green */
}

h2{
color: hsla(120, 100%, 50%, 1); /* green */
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>