CSS - Function

About

A css function is a function that can be used in a CSS property value to calculate complex styling requirement.

Example

: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, …)

2)

  • Comparison Functions: min(), max(), and clamp()
  • Stepped Value Functions: round(), mod(), and rem()
  • Trigonometric Functions: sin(), cos(), tan(), asin(), acos(), atan(), and atan2()
  • 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)

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>

Other colors function

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.

Not supported fully

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:

Powered by ComboStrap