Create reusable CSS logic with @function

You can now write custom functions in CSS.

You can keep reusable functions in a functions.css or utils.css file, much like a utils.js file alongside your reset.css.

Here is what that can look like:

/* Return the negative of any value */
@function --negate(--value) {
	result: calc(-1 * var(--value));
}

/* Return a color with a custom alpha value */
@function --opacity(--color, --opacity) {
	result: rgb(from var(--color) r g b / var(--opacity));
}

/* Return a fluid font-size value */
@function --fluid-type(--font-min, --font-max, --type: 'header') {
	--scalar: if(
		style(--type: 'header'): 4vw;
		style(--type: 'copy'): 0.5vw
	);

	result: clamp(
		var(--font-min),
		var(--scalar) + var(--font-min),
		var(--font-max)
	);
}

The function name starts with --, parameters behave like local custom properties, and result defines the returned value.

@function is still experimental and has limited browser availability. Treat it as progressive enhancement or use it in a controlled browser environment for now.

You Don’t Need JavaScript ebook mockup

I wrote a guide about building modern UI with HTML and CSS first. It covers practical patterns you can use before reaching for JavaScript.

Learn more

    No strings attached, unsubscribe anytime!

    Other short articles you might like

    Explore more articles on front-end development, covering HTML, CSS and JavaScript for building high-performance websites.