2 min read

CSS Functions

CSS Functions are used as values for various CSS properties. They can perform calculations, retrieve values, manipulate colors, define shapes, and more.

1. attr()

The attr() function retrieves the value of an attribute of the selected element and uses it in the stylesheet. It is most commonly used with the content property in pseudo-elements.

/* Display the href attribute value after links */
a::after {
  content: " (" attr(href) ")";
}

Note: While the spec allows attr() to be used for other properties (like width), browser support is currently limited mostly to content.

2. url()

The url() function is used to include a file. It takes an absolute or relative URL as its parameter.

body {
  background-image: url("images/bg.png");
}

@font-face {
  font-family: 'MyFont';
  src: url('myfont.woff2');
}

3. var()

The var() function is used to insert the value of a custom property (CSS variable).

:root {
  --main-color: blue;
}

div {
  color: var(--main-color);
}

4. Math Functions

CSS provides powerful mathematical functions for dynamic values.

  • calc(): Performs calculations (width: calc(100% - 20px)).
  • min(): Uses the smallest value.
  • max(): Uses the largest value.
  • clamp(): Clamps a value between a minimum and maximum.

5. Color Functions

  • rgb() / rgba(): Red, Green, Blue, (Alpha).
  • hsl() / hsla(): Hue, Saturation, Lightness, (Alpha).
  • color-mix(): Mixes two colors together in a given color space.
    color: color-mix(in srgb, red, blue); /* Purple */

6. Other Common Functions

  • repeat(): Used in Grid Layout to repeat columns/rows.
  • minmax(): Used in Grid Layout to define a size range.
  • fit-content(): Clamps a given size to the available size.

programming/css/css programming/css/calc-function programming/css/math-functions programming/css/css-variables