EthicsComputerCourses
Join training +91 90532 10052

CSS Functions

CSS · Lesson 95 of 240 Intermediate 10 min read Updated

By the end of this lesson you will be able to recognise every common CSS function, know which family it belongs to, and pick the right one for a job. You will try the newer maths functions round(), mod(), rem(), abs() and sign(), mix colours with color-mix(), and read HTML attributes into CSS with attr(). Each family links to the lesson that covers it in depth.

You should know CSS calc(), min(), max() and CSS Variables & Dynamic Themes first.

What a CSS function is

A CSS function is a name followed by brackets, with inputs inside: name(input, input). The browser takes the inputs and gives back one value, such as a length, a colour or an image. That value is then used by the property.

Think of a mixer grinder. You put in ingredients, press a button, and get one result. color-mix() takes two colours and an amount and returns one new colour, in the same way.

Two syntax rules matter:

  • There is no space between the name and the bracket. calc (100% - 1rem) is invalid; calc(100% - 1rem) works.
  • If anything inside is wrong, the whole declaration is ignored, and the browser keeps the previous valid value for that property. This is different from a bad var() value, which you saw in the last lessons.

CSS has many functions, but they fall into a few families.

FamilyExamplesReturns
Mathscalc(), min(), max(), clamp(), round(), mod()A number, length, angle or time
Colourrgb(), hsl(), oklch(), color-mix(), light-dark()A colour
Imageurl(), linear-gradient(), image-set()An image
Referencevar(), attr(), env()A value stored somewhere else
Transformtranslate(), rotate(), scale()One step of a transform
Filterblur(), brightness(), drop-shadow()One step of a filter

Maths functions

You already know the core four. calc(), min() and max() are covered in CSS calc(), min(), max(), and clamp() in clamp() & Fluid Typography. They have worked in all browsers for years.

Newer maths functions round, wrap and check signs:

FunctionWhat it doesExample resultBaseline
round(strategy, A, B)Rounds A to a multiple of Bround(up, 101px, 25px) is 125px2024
mod(A, B)Remainder; sign follows Bmod(-7, 3) is 22024
rem(A, B)Remainder; sign follows Arem(-7, 3) is -12024
abs(A)Removes the minus signabs(-12px) is 12px2025
sign(A)-1, 0 or 1sign(-3px) is -12025

The rounding strategy can be nearest (the default), up, down or to-zero. round(), mod() and rem() became Baseline Newly available in May 2024; abs() and sign() in June 2025. There are also trigonometry functions (sin(), cos(), tan()) and pow(), sqrt() for advanced effects, all Baseline since 2023.

mod() and rem() differ only for negative numbers. A clock is a good picture for mod(): going 7 hours back from 0 on a 3-hour dial lands you on 2, never on a negative hour.

Step 1: rounding marks to grade bands

A school report shows each student's exact marks and their grade band, rounded down to the nearest 10. Because these functions are newer, the rounded bar sits inside @supports, so older browsers simply show the exact bar. See @supports Feature Queries for more.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>round() for grade bands</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 1rem; }
    .student { width: min(100%, 26rem); margin-bottom: 1rem; }
    .bar { height: 0.7rem; margin-top: 0.25rem; border-radius: 4px; }
    .exact { width: calc(var(--marks) * 1%); background: oklch(60% 0.13 250); }
    .band  { width: calc(var(--marks) * 1%); background: oklch(70% 0.15 60); }
    @supports (width: round(down, 10%, 10%)) {
      .band { width: round(down, var(--marks) * 1%, 10%); }
    }
  </style>
</head>
<body>
  <h1>Class 8 science results</h1>
  <div class="student" style="--marks: 67">
    Aarav: 67 marks
    <div class="bar exact"></div>
    <div class="bar band"></div>
  </div>
  <div class="student" style="--marks: 92">
    Meera: 92 marks
    <div class="bar exact"></div>
    <div class="bar band"></div>
  </div>
  <div class="student" style="--marks: 48">
    Rohan: 48 marks
    <div class="bar exact"></div>
    <div class="bar band"></div>
  </div>
</body>
</html>

The blue bar shows the exact marks. The orange bar snaps down to the band: 67 becomes 60%, 92 becomes 90% and 48 becomes 40%. Change down to nearest and run it again: Aarav's band jumps to 70%.

Colour functions

FunctionUse it forDeep dive
rgb()Red, green and blue amounts, as in hex codesRGB, RGBA & HEX Colors
hsl()Hue, saturation and lightness, easy to adjust by handHSL & HSLA Colors
oklch()Lightness, chroma and hue that look even to the eye (Baseline 2023)CSS Colors
color-mix()Blending two colours by a percentage (Baseline 2023)Relative Colours & Wide-gamut Colour
light-dark()One colour for light mode, one for dark (Baseline 2024)Dark Mode Using CSS

Modern colour functions separate values with spaces and use / before the transparency: rgb(255 120 0 / 50%). The older comma form rgba(255, 120, 0, 0.5) still works, but do not mix the two styles in one function.

Step 2: a palette from one brand colour

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Colour functions</title>
  <style>
    :root { --brand: oklch(58% 0.16 45); }
    body { font-family: system-ui, sans-serif; padding: 1rem; }
    .swatches { display: flex; flex-wrap: wrap; gap: 0.5rem; }
    .swatches div {
      width: 7rem;
      padding: 1.5rem 0.5rem 0.5rem;
      border-radius: 8px;
      font-size: 0.8rem;
    }
    .s1 { background: color-mix(in oklch, var(--brand), white 80%); }
    .s2 { background: color-mix(in oklch, var(--brand), white 40%); }
    .s3 { background: var(--brand); color: white; }
    .s4 { background: color-mix(in oklch, var(--brand), black 35%); color: white; }
    .s5 { background: rgb(0 0 0 / 15%); }
  </style>
</head>
<body>
  <h1>Farhan's Mithai Shop palette</h1>
  <div class="swatches">
    <div class="s1">80% white</div>
    <div class="s2">40% white</div>
    <div class="s3">Brand</div>
    <div class="s4">35% black</div>
    <div class="s5">Black at 15%</div>
  </div>
</body>
</html>

You should see five swatches: two pale tints, the brand orange, a deep shade, and a see-through grey. Change only --brand to another oklch() value and the whole palette follows.

Image functions

Anywhere CSS accepts an image, such as background-image, you can use an image function:

  • url() loads a file: url("{{samples}}/landscape.svg").
  • linear-gradient(), radial-gradient() and conic-gradient(), plus their repeating- versions, draw an image from colours. See CSS Gradients and CSS Gradients: Advanced.
  • image-set() offers several files and lets the browser pick one by screen sharpness or format. It is Baseline since 2023. See Responsive Images.
CSS
.hero {
  background-image: image-set(
    url("hero.avif") type("image/avif"),
    url("hero.jpg") type("image/jpeg")
  );
}

Reference functions

These read a value from somewhere else.

  • var(--name, fallback) reads a custom property. You know it well from CSS Custom Properties.
  • attr(data-price) reads an HTML attribute. In the content property of ::before and ::after, it returns text and works in every browser. See Pseudo-Elements.
  • env(safe-area-inset-bottom) reads a value from the device, such as the space taken by a phone's notch or home bar. See Fixed Positioning.

Transform, filter and other function families

Some properties take a list of functions, applied one after another, like steps in a recipe.

FamilyFunctionsPropertyDeep dive
Transformstranslate(), rotate(), scale(), skew(), matrix()transform2D Transformations, 3D Transformations
Filtersblur(), brightness(), contrast(), grayscale(), drop-shadow()filter, backdrop-filterCSS Filters, Backdrop Filter
Shapescircle(), ellipse(), inset(), polygon()clip-path, shape-outsideCSS Clip-Path, CSS Shapes
Gridrepeat(), minmax(), fit-content()grid-template-columnsGrid Template Columns
Easingcubic-bezier(), steps(), linear()transition, animationTransition Timing Functions

Order matters in a list. transform: translateX(2rem) rotate(45deg) moves first and then spins. Swap them and the element spins first, so it moves along a tilted direction and ends somewhere else.

Step 3: one card, many families

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Function families</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 2rem 1rem; }
    .offer {
      position: relative;
      width: min(100%, 20rem);
      padding: 1.5rem 1rem;
      color: white;
      background: linear-gradient(135deg, oklch(60% 0.18 30), oklch(55% 0.17 340));
      clip-path: polygon(0 0, 100% 0, 100% 85%, 50% 100%, 0 85%);
      padding-bottom: calc(1.5rem + env(safe-area-inset-bottom, 0px));
    }
    .wrap { filter: drop-shadow(0 6px 8px rgb(0 0 0 / 30%)); }
    .offer h2 { margin-top: 0; padding-right: 4.5rem; }
    .offer [data-price]::after { content: " ₹" attr(data-price); font-weight: 700; }
    .tag {
      position: absolute;
      top: 0.75rem;
      right: 0.75rem;
      padding: 0.2rem 0.5rem;
      background: white;
      color: oklch(45% 0.17 30);
      transform: rotate(8deg) scale(1.1);
    }
  </style>
</head>
<body>
  <div class="wrap">
    <section class="offer">
      <span class="tag">Diwali</span>
      <h2>Ananya's Sweets, Kochi</h2>
      <p data-price="499">Dry fruit box, 500 g:</p>
    </section>
  </div>
</body>
</html>

This card uses six families: min() and calc() for size, oklch() and rgb() for colour, linear-gradient() for the image, polygon() for the pointed shape, drop-shadow() on the wrapper, and rotate() with scale() for the tag. The price comes from the HTML through attr(). The shadow sits on the wrapper because clip-path would cut off a shadow drawn on the card itself.

Common mistakes

  • A space before the bracket. rgb (0 0 0) is invalid. Write rgb(0 0 0).
  • Mixing comma and space syntax. rgb(255 0 0, 0.5) is invalid. Use rgb(255 0 0 / 50%).
  • Using new functions with no fallback. Put round(), abs() or typed attr() inside @supports, with a simpler value before it.
  • Expecting attr() to give a number in any property. In Baseline browsers it returns text, for content only.
  • Ignoring order in function lists. translate() then rotate() is not the same as rotate() then translate().

Interview questions

1. What happens if a CSS function in a declaration is invalid?

The browser drops the whole declaration while parsing and keeps the previous valid value for that property. This differs from a bad var() value, which is only found at computed-value time and makes the property act as unset.

2. What is the difference between mod() and rem()?

Both return a remainder. With mod() the result takes the sign of the divisor, so mod(-7, 3) is 2. With rem() it takes the sign of the dividend, so rem(-7, 3) is -1. They give the same answer when both inputs are positive.

3. Where can you use attr() today, and what is still limited?

attr() in the content of a pseudo-element returns the attribute as text and works in all browsers. Typed attr(), which returns lengths or numbers for any property, is supported in Chromium and recent Firefox but not Safari, so it is not Baseline yet.

4. Why does the order of transform functions matter?

Each function works in the coordinate system left by the previous one. Translating and then rotating moves the element and spins it in place, while rotating first turns the axes, so the later translate moves it along a tilted line.

5. When would you use color-mix() instead of writing a second colour?

When a colour should be derived from a token, such as a hover shade or a pale background. color-mix(in oklch, var(--brand), white 80%) updates automatically when --brand changes, so a rebrand needs only one edit.

Key points

  • A CSS function is name(inputs) with no space before the bracket; it returns one value.
  • Maths: calc(), min(), max(), clamp(), plus round(), mod(), rem() (Baseline 2024) and abs(), sign() (Baseline 2025).
  • Colour: rgb(), hsl(), oklch(), color-mix() and light-dark(), with space-separated syntax.
  • Image: url(), gradient functions and image-set().
  • Reference: var(), attr() (text in content; typed form not Baseline) and env().
  • Transform, filter, shape, grid and easing functions are applied in the order you write them.

Exercise

Make a festival price tag for a Lucknow sweet shop. Use oklch() for the main colour and color-mix() for a pale background tint. Show the price from a data-price attribute with attr(). Rotate the tag slightly with rotate(). Finally, show a "per kg" price bar whose width is round(nearest, ...) to the nearest 25%, inside @supports, with a plain calc() width as the fallback.

Show solution
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Price tag</title>
  <style>
    :root { --accent: oklch(55% 0.17 20); }
    body { font-family: system-ui, sans-serif; padding: 2rem; }
    .tag {
      width: min(100%, 16rem);
      padding: 1rem;
      border: 3px solid var(--accent);
      background: color-mix(in oklch, var(--accent), white 85%);
      transform: rotate(-3deg);
    }
    .tag [data-price]::after { content: " ₹" attr(data-price); font-weight: 700; color: var(--accent); }
    .bar { height: 0.5rem; background: var(--accent); width: calc(var(--fill) * 1%); }
    @supports (width: round(nearest, 10%, 25%)) {
      .bar { width: round(nearest, var(--fill) * 1%, 25%); }
    }
  </style>
</head>
<body>
  <div class="tag">
    <h2>Lucknow Sweets</h2>
    <p data-price="640">Malai gilori, per kg:</p>
    <div class="bar" style="--fill: 64"></div>
  </div>
</body>
</html>

color-mix() builds the tint from the same accent, attr() prints ₹640 from the HTML, and the bar snaps from 64% to 75% in browsers that support round().

Quick Quiz

1. What does round(up, 101px, 25px) return?

2. Which declaration is valid?

3. Which use of attr() works in every major browser today?

4. What is mod(-7, 3)?

Learn CSS with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call