This feature is coming to CSS. It's part of the CSS Houdini API.
It's not in browsers yet. This repo was inspired by it.
Custom functions look like this:
<style class="functions">
body {
background: random-color();
}
</style>You can give them params:
div > p {
font-size: rand(.8em, 1em, 1.2em);
}Functions will be able to use variables:
div {
--semantic: false;
}
section {
--semantic: true;
}
div p, section p {
color: if(--semantic, black, red);
}🌌 What are custom functions?
It's a func() just like calc() or rgb(), inside your CSS.
🌄 What does it do?
Custom functions have two important purposes.
- It can help you write less complicated CSS.
- It adds wholey new features to CSS. When you use a custom function, the function generates additional CSS, small or large, as long as that custom function is defined in JS using this API.
🌆 How does it work?
This JavaScript library doesn't add any specific functions, but provides an API
to allow you to create your own - or use others. By default, it only generates
CSS, so running your custom functions won't create expensive JS payloads.
It works by scanning your document for <style> elements that have class="functions".
Using CSS selectors to set HTML attributes:
a {
/** sets target="_blank" on all <a> elements */
--target: aria("_blank");
--role: aria("button");
}Edit HTML to turn text into spans to animate:
.spooky {
--delay: animate-letters(.5, 4);
}
.spooky > span {
animation: spook-text 4s ease-in-out var(--delay) infinite;
}Add many media queries options in one line:
body {
--sizes: width(720px, 1080px);
}
nav {
display: grid;
grid-template-columns: switch(--sizes,
1fr, /** 0px - 720px */
1fr 1fr 1fr, /** 720px - 1080px */
1fr 1fr 1fr 1fr); /** +1080px */
}Import customFunctions then .add(fn) the new function.
import { customFunctions } from "css-functions.js"
customFunctions.add(pointer => {
const color_choices = ["red","blue","green"]
const num = Math.floor(Math.random() * color_choices.length)
return color_choices[num]
}, "random-color")This adds the color: random-color(); function. It can be used
anywhere in CSS that takes a color name.
The pointer parameter.
When you add a function, that code will run anytime you use the function in CSS!
Your function will get passed one parameter. It's a CssPointer from the css-helper-class.js
file.
Take a look at the file, or download to see how it works.
When your function runs, the CssPointer has key details on your CSS where your function was called. Here's the properties:
.selectorlike.card header h3.propertythe property name where you used your functionfont-size.elementsthe elements on the page that match the selector.paramsa list of params passed to your function ifrgb(12, 200, 30)then["12", "200", "30"].placeholdernot often needed this is the generated CSS variable that will replace your function.
Notes:
- Must be inside a
<style class="functions">element. CssPointer.applyis for variables ifvar()is missing.
References:
@/BobobUnicorn, Chrome labs