About
A css function is a function that can be used in a CSS property value to calculate complex styling requirement.
Example
- Css function are mostly used with CSS Variable. Below we define the space unit variable to be 1.5em for the whole page (root)
:root {
--space-unit: 1.5em
}
- We use it then to define the padding of a note block
.note {
padding : calc(1.5 * var(--space-unit));
background-color: skyblue;
}
<div class="note">A note with a 1.5 padding of the space unit</div>
- The output is:
List
Mathematics
Calc
The calc() 1) function allows mathematical expressions with addition (+), subtraction (-), multiplication (*), and division (/) to be used as component values.
Example:
section {
width: calc(100%/3 - 2*1em - 2*1px);
}
p {
margin: calc(1rem - 2px) calc(1rem - 1px);
}
Others (min, max, …)
- Comparison Functions: min(), max(), and clamp()
- Stepped Value Functions: round(), mod(), and rem()
- Exponential Functions: pow(), sqrt(), hypot(), log(), exp()
- Sign-Related Functions: abs(), sign()
- Numeric Constants: e, pi
Image
Image Css function 3) are mainly css gradient functions that create images. See the Gradient functions section for example
- linear-gradient
- radial-gradient
- repeating-linear-gradient
- conic-gradient
Positioning / Transform
Inside a transform property 4)
- translate 5) is a postioning function
transform: translate(100px, 200px);
Color Function
color-mix
The color-mix 6) function is the color mixture linear interpolation function . Supported only since the css level 5, check your target browser
#red {
background-color: red; /* [255,0,0] */
}
#green {
background-color: green; /* [0,255,0] */
}
#mix {
background-color: color-mix(in lch, red 50%, green, 50%); /* [128,128,0] olive - half red - half green */
}
.swatch {
display: inline-block;
width: 3em;
height: 3em;
}
- The HTML
<div id="red" class="swatch"></div>
<div id="green" class="swatch"></div>
<div id="mix" class="swatch"></div>
- The output: In a supporting browser, the third watch should be olive.
Other colors function
- color-contrast 7) to select the most contrasting color
- lch 11) to specify a lch / hcl color
- hwb 12) to specify a hwb color (in the hwb colorspace)
- and more …
Attr
The attr() function 13) is allowed as a component value in properties applied to an element or pseudo-element. It returns the value of an attribute on the element.
The attr function is for now supported only for the content property. See https://caniuse.com/?search=attr
Because:
- In CSS2.1, the attr() expression always returns a string (no number)
- In CSS3, the attr() expression can return many different types (ie may take number)
Example based on css2.1
- The html
<span class="inline-note" data-content="Prefix: ">My Inline note with a prefix</span>
- The css
.inline-note::before {
content: attr(data-content);
}
- output: