CSS functions extend CSS to give it a more “programming language” set of features, i.e. we can create functions, with parameters, even add type safety and return values.
Let’s start by looking at the basic syntax on a simple function which returns a given value depending on the “responsive design” size.
@function --responsive(--sm, --md, --lg: no-value) {
result: var(--lg);
@media(width <= 600px) {
result: var(--sm);
}
@media(width > 600px) and (width <= 800px) {
result: var(--md);
}
@media(width > 800px) {
result: var(--lg);
}
}
What’s happening here is the function is declared with the @function and the name (in this case responsive) is prefixed with — as are any parameters. Hence we have three parameters, the first is what’s return if the width is <= 600px and so on. The result: is not quite equivalent to a return as it does not shortcut and return a value, instead if you set the result: later then the last result is used as the “returned value”.
Here’s an example of us setting a 200px square with different colours upon the different break points
div {
width: 200px;
height: 200px;
background: --responsive(
blue,
green,
red);
}
We can also supply default values to a function, for example we could set a default “no-value” using
@function --responsive(--sm, --md, --lg: no-value)
Here’s an example of us setting other defaults with values
@function --responsive(--sm: blue, --md: green, --lg: red)
Interestingly we can also make things type safe, for example let’s set each parameter as being a color and the return value also being of type color
@function --responsive(--sm <color>: blue, --md <color>: green, --lg <color>: red) returns <color>
We can also supply multiple types, so let’s assume we want a –opacity function where the amount can be a percentage or number, then we might write something like
@function --opacity(--color, --opacity type(<number> | <percentage>): 0.5) returns <color> {
result: rgb(from var(--color) r g b / var(--opacity));
}
and in usage
div {
width: 200px;
height: 200px;
background: --opacity(blue, 80%);
/* background: --opacity(blue, 0.3); */
}