What are CSS Functions

Before we move on to the more advanced topics in CSS, there are some core concepts we must discuss. The first one is the function.

Functions are special statements in CSS that add programmatic characteristics to the language. A function accepts one or more inputs and returns an output, which is then assigned to the CSS property.

For example, the rgb() function we discussed before accepts three values as the input and returns the corresponding color code as the output. The color code is then assigned to the color property.

css
1p {
2  color: rgb(168, 189, 45);
3}

There are dozens of different functions available in CSS, and you can find a complete reference here.

Discussing all of them in one lesson is impossible as some of those functions are quite advanced. Instead, we will talk more about them as we encounter specific examples in the future.

In this lesson, we will discuss a very special and helpful function called var(). This will give you a better idea of what functions are and what they do.

This particular function var() allows you to retrieve a user-defined variable.

css
1:root {
2  --primary-color: salmon;
3}
4
5p {
6  color: var(--primary-color);
7}

The variables are defined in the :root section. :root is a pseudo-selector that matches the HTML document's root element, which is <html>.

In this example, --primary-color is the variable name, and salmon is the variable value. The var() function accepts the variable name as the input and returns its value as the output.

Open demo in new tab

This method of defining styles is very useful because you can reuse the same variables in different locations of the CSS file. When designing a webpage, you'll want to keep your design language consistent.

For instance, if you want skyblue to be your primary accent color, you'll need to use that value in many different places across your entire CSS file.

css
1a {
2  color: skyblue;
3}
4
5button {
6  background-color: skyblue;
7}
8
9/* . . . */

But that means you must edit multiple lines when changing your primary color. In a large-scale project, that is easy to lead to errors.

A better way to organize your code is to put this information in the :root section as variables and then access them later in the code using the var() function. When you need to change the accent color, all you need to do is changing the corresponding variable.

css
1:root {
2  --primary-color: skyblue;
3}
4
5a {
6  color: var(--primary-color);
7}
8
9button {
10  background-color: var(--primary-color);
11}

Of course, this method is not limited to colors. You can define anything you want, such as the font family, font size, width and height, etc.

css
1:root {
2  --primary-color: skyblue;
3  --font-size: 16px;
4  --font-family: Cambria, Cochin, Georgia, Times, "Times New Roman", serif;
5}
6
7p {
8  border: var(--primary-color) solid 2px;
9  font-size: var(--font-size);
10  font-family: var(--font-family);
11}