4 Useful CSS Functions That You Should Know
Learn about CSS functions with practical examples
Introduction
Like any other language, CSS has its own functions. They can be inserted where you’d place a value, or in some cases, accompanying another value declaration. Some CSS functions even let you nest other functions within them.
In this article, we will learn about some amazing CSS functions that you should know. Let’s get right into it.

1. CSS attr function
The function attr()
returns the value of an attribute of the selected elements. It allows us to reach into HTML, snag an attribute’s content, and feed it to the CSS content property.
Have a look at the example below:
/* <div data-example="Medium"></div> */ div:after {
content: attr(data-example);
}
The example below will display the attribute Medium
on the page. You can try it on your web page.
Here is the Codepen example:
2. The calc function
The function calc()
allows you to perform calculations to determine CSS property values. It is supported by all the major browsers.
This function takes two arguments and calculates a result from the operator (+
, -
, *
, /
) you supply it, provided those arguments are numbers with or without an accompanying unit.
Here is an example:
.element { width: calc(100vw - 80px); }
Here is a Codepen example calculating the width of a div element using the function calc()
.
3. The var function
The function var()
is used to insert the value of a CSS variable. This will be useful to create some CSS variables in order to use them in many places on our code.
Have a look at the example below:
:root {
--main-bg-color: coral;
--main-txt-color: blue;
--main-padding: 15px;
}
#div1 {
background-color: var(--main-bg-color);
color: var(--main-txt-color);
padding: var(--main-padding);
}
#div2 {
background-color: var(--main-bg-color);
color: var(--main-txt-color);
padding: var(--main-padding);
}
As you can see above, we created our values in the root element, then we used them in our div elements using the function var()
.
4. The filter function
The function filter()
applies graphical changes to the appearance of an input image and elements. The effects we can achieve are as follows: ( blur
, brightness
, contrast
, grayscale
, hue-rotate
, opacity
, invert
, sepia
, saturate
, drop-shadow
). I think there are more if I’m not wrong.
Here is an example:
.element1 {
filter: drop-shadow(0.25rem 0 0.75rem #ef9035);
}
// Or:.element2 {
filter: blur(20px);
}
Here is another Codepen example of the filter function:
Conclusion
As you can see, functions in CSS are very useful and important. You may be familiar with some CSS functions, but the language has a surprisingly expansive list. There are a lot more useful functions that you will need to learn about.
Thank you for reading this article, I hope you found it useful.