Custom Functions in CSS
CSS already has plenty of useful functions, like calc() , min() , max() , and clamp() . They let you build more flexible styles without repeating the same logic. CSS custom functions let you take this idea a little further. The @function at-rule lets you define your own functions, pass them values, and return a result that you can use in your styles. Syntax Before we build anything, let's quickly…
CSS already offers useful functions like calc(), min(), max(), and clamp(). These functions allow developers to create more adaptable styles without repeating logic. CSS custom functions expand on this idea, enabling users to define their own functions, pass values, and receive results.
The @function at-rule is used to define custom functions, with the function name and parameters both starting with double dashes. Parameters define the values passed into the function, while result specifies what the function returns. Parameters can have type and default values.
A simple function, --double(), doubles a value using the calc() function. It can be used in CSS styles like this: .box { width: --double(100px); }. This results in a width of 200px.
Custom functions can accept multiple parameters, allowing them to be used with varied inputs. A function named --transparent() uses relative color syntax to transform a hex code into a transparent background. It accepts two parameters: --color, a required color value, and --alpha, an optional parameter that defaults to 0.8.
Custom functions can also include type declarations and default values for parameters. They can define custom properties within the function that act like local variables. This allows the function to produce different results based on the environment, such as screen width. For instance, a function named --narrow-wide() returns one value for narrow screens and another for wider screens using the @container rule.
In summary, CSS custom functions enable developers to package and reuse CSS logic, making styles more adaptable and maintainable. They can accept multiple parameters, include type declarations, default values, and conditional returns based on environment conditions.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.