Functions Stay organized with collections Save and categorize content based on your preferences.
The CSS Podcast - 020: Functions
So far in this course, you've been exposed to several CSS functions.In thegrid module,you were introduced tominmax() andfit-content(),which help you size elements.In thecolor module,you were introduced torgb(), andhsl(), which help you define colors.
Like many other programming languages,CSS hasa lot of built-in functionsthat you can access whenever you need them.
Every CSS function has a specific purpose,in this lesson, you'll get a high-level overview,giving you a much better understanding of where and how to use them.
What is a function?
A function is a named, self-contained piece of code that completes a specific task.A function is named so you can call it within your code and you can pass data into the function.This is known as passing arguments.
A lot CSS functions arepure functions,which means that if you pass the same arguments into them,they will always give you the same result back,regardless of what is happening in the rest of your code.These functions will often re-compute as values change in your CSS,similar to other elements in the language,such as computed cascaded values likecurrentColor.
In CSS, you can only use the provided functions,rather than write your own,but functions can be nested within each other in some contexts,giving them more flexibility.We'll cover that in more detail, later in this module.
Functional selectors
.post:is(h1,h2,h3){line-height:1.2;}You learned about functional selectors in thepseudo-classes modulewhich detailed functions like:is() and:not().The arguments passed into these functions are CSS selectors,which are then evaluated.If there is a match with elements,the rest of theCSS rule will be applied to them.
Custom properties andvar()
:root{--base-color:#ff00ff;}.my-element{background:var(--base-color);}A custom property is a variable which lets you tokenize values in your CSS code.Custom properties are also affected by the cascadewhich means they can be contextually manipulated or redefined.A custom property must be prefixed with two dashes (--) and are case sensitive.
Thevar()function takes one required argument:the custom property that you are trying to return as a value.
In the preceding snippet, thevar() function has--base-color passed as anargument. If--base-color is defined, thenvar() will return the value.
.my-element{background:var(--base-color,hotpink);}You can also pass a fallback declaration value into thevar() function.This means that if--base-color can't be found,the passeddeclaration will be used instead, which in this sample's case is thehotpink color.
Functions that return a value
Thevar() function is just one of the CSS functions that return a value.Functions likeattr() andurl() follow a similar structure tovar()—you pass one or more arguments and use them on theright side of your CSS declaration.
a::after{content:attr(href);}Theattr() function hereis taking the content of the<a> element'shref attributeand setting it as thecontent of the::after pseudo-element.If the value of the<a> element'shref attribute was to change,this would automatically be reflected in thiscontent attribute.
.my-element{background-image:url('/path/to/image.jpg');}Theurl() function takes astring URL and is used to load images, fonts and content.If a valid URL isn't passed in or the resource that the URL points to can't be found,nothing will be returned by theurl() function.
Color functions
You learned all about color functions in thecolor module.If you haven't read that one yet, it is strongly recommended that you do.
Some available color functions in CSS arergb(),hsl(),lab(),lch(),oklab(),oklch(), andcolor().All of these have a similar form where configuration arguments are passed in and a color is returned back.
Mathematical expressions
Like many other programming languages,CSS provides useful mathematical functions to assist with various types of calculation.
Arithmetic functions
calc()
Thecalc()function takes a single mathematical expression as its parameter.This mathematical expression can be a mix of types,such as length, number, angle and frequency. Units can be mixed too.
.my-element{width:calc(100%-2rem);}In this example, thecalc() function is being used to size an element's widthas 100% of its containing parent element,then removing2rem off that computed value.
:root{--root-height:5rem;}.my-element{width:calc(calc(10%+2rem)*2);height:calc(var(--root-height)*3);}Thecalc() function can be nested inside anothercalc() function.You can also pass custom properties in avar() function as part of an expression.
min() andmax()
Themin()function returns the smallest computed value of the one or more passed arguments.Themax()function does the opposite: get the largest value of the one or more passed arguments.
.my-element{width:min(20vw,30rem);height:max(20vh,20rem);}In this example,the width should be the smallest value between20vw—which is 20% of theviewport width—and30rem.The height should be the largest value between20vh—which is 20% of theviewport height—and20rem.
vw andvh in thesizing units module.clamp()
Theclamp()function takes three arguments: the minimum size,the ideal size and the maximum.
h1{font-size:clamp(2rem,1rem+3vw,3rem);}In this example, thefont-size will be fluid based on the width of the viewport.Thevw unit is added to arem unit to assist with screen zooming,because regardless of zoom level avw unit will be the same size.Multiplying by arem unit—based on the root font size—provides theclamp() function with a relative calculation point.
You can learn more about themin(),max(), andclamp() functions inthis article on these functions.
Trigonometric Functions
Trigonometric functions allow you to find any point on a circle based on anangle, model cyclical phenomena such as sound waves, describe orbits, and more.In CSS, you can use trigonometric functions to set properties based on rotation,time animations, rotate elements based on a point, and other uses.
For more information and examples, see ourarticle ontrigonometric functions.
sin(),cos(), andtan()
Thesin(),cos(), andtan() functions take an angle argument and returnthe sine, cosine, and tangent respectively. Thesin() andcos() functionsreturn a number between-1 and1. Thetan() function returns a numberbetween-Infinity and+Infinity. The angle argument can be any supportedangle unit.
:root{--sine-degrees:sin(45deg);/* returns 0.7071 */--sine-radians:sin(0.7853rad);/* returns 0.7071 */}In the preceding example,--sine-degrees and--sine-radians have the samevalue (in this case0.7071).
In the preceding example, thesin() andcos() functions are used to createoscillating animations on thex andy axes by multiplying the result by thespecified radius. Using both functions at once allows an orbiting animation.We use acustom property,--angle, to smoothlyanimate the angle for all function calls.
asin(),acos(), andatan()
Theasin(),acos(), andatan() are the inverse of thesin(),cos(),andtan() functions, taking a number as an argument and returning an anglevalue between-90deg and90deg. Theasin() andacos() functions accepta number between-1 and1 while theatan() function accepts a numberbetween-Infinity and+Infinity.
:root{--degrees:asin(0.7071);/* returns 45deg */}atan2()
Theatan2() function takes two arguments representing a point relative to theorigin and returns the angle representing the direction to that point. You canuse this to rotate elements to face a specific point. The arguments can benumbers, size units, or a percentage, but both arguments must both be the samekind.
In the example above theatan2() function is used to determine the anglebetween the center of the viewport and the current mouse position. Note that they value is the first argument, and thex value is the second. The angle isthen used to position the "pupils" relative to the center of the "eyes", so theyfollow the mouse.
hypot()
Thehypot() function takes two length arguments representing the sides of aright triangle and returns the length of the hypotenuse. You can use this as ashortcut for calculating this using exponential functions. Both arguments mustbe the same unit type andhypot() will return the same type.
:root{--use-ems:hypot(3em,4em);/* returns 5em */--use-px:hypot(30px,40px);/* returns 50px */}Exponential functions
pow() andexp()
Thepow() function takes two numeric arguments, the base and the exponent, andraises the base by the power of the exponent. Both arguments must be numberswithout units. Theexp() function takes a single argument and is equivalent tocalling thepow() function with a base ofe.
.my-element{width:calc(10px*pow(4,2);/* 10px * (4 * 4) == 160px */}sqrt()
Thesqrt() function takes a numeric argument and returns its square root. Theargument cannot include units.
:root{--root:sqrt(25);/* returns 5 */}log()
Thelog() function returns thelogarithm of a numeric value. If oneargument is passed, it will return thenatural logarithm. If asecond argument is passed, thelog() function will use the second argument asthe base for the logarithm.
:root{--log2:log(16,2);/* returns 4 */--logn:log(16);/* returns 2.7725 */}Sign related functions
abs()
Theabs() function takes a numeric argument and returns the absolute(positive) value of the argument value.
.my-element{color:rgba(0,0,0,abs(-1));}In the preceding example, analpha value of-1 would result in transparenttext, but theabs() function returns the absolute value of1, which resultsin fully opaque text.
sign()
Thesign() function takes a numeric argument and returns the arguments sign.Positive values return1 and negative values return-1. Zero values return0.
.my-element{top:calc(50vh+25vh*sign(var(--value));}In the preceding examples, if--value is positive, the top value will be75vh. If it is negative the, top value will be25vh. If it is zero, the topvalue will be50vh.
Shapes
Theclip-path,offset-path andshape-outsideCSS properties use shapes to visually clip your box or provide a shape for content to flow around.
There are shape functions that can be used with both of these properties.Simple shapes such ascircle(),ellipse() andinset()take configuration arguments to size them.More complex shapes, such aspolygon()take comma separated pairs of X and Y axis values to create custom shapes.
.circle{clip-path:circle(50%);}.polygon{clip-path:polygon(0%0%,100%0%,100%75%,75%75%,75%100%,50%75%,0%75%);}Likepolygon(), there is also apath() function which takes an SVG fill rule as an argument.This allows for highly complex shapes that can be drawn in a graphics toolsuch as Illustrator or Inkscape and then copied into your CSS.
Transforms
Lastly in this overview of CSS functions are the transform functions,which skew, resize and even change the depth of an element.All of the following functions are used with thetransform property.
Rotation
You can rotate an element using therotate()function, which will rotate an element on its center axis.You can also use therotateX(),rotateY() androtateZ()functions to rotate an element on a specific axis instead.You can pass degree, turn and radian units to determine the level of rotation.
.my-element{transform:rotateX(10deg)rotateY(10deg)rotateZ(10deg);}Therotate3d()function takes four arguments.
The first 3 arguments are numbers, which define the X, Y and Z coordinates.The fourth argument is the rotation which,like the other rotation functions, accepts degrees, angle and turns.
.my-element{transform:rotate3d(1,1,1,10deg);}You can use the individualrotate property to rotatean element. When used outside of thetransform property, you can transition itseparately from other transformations. It accepts similar values to the rotatefunctions.
Scale
You can change the scaling of an element withtransform and thescale() function.The function accepts one or two numbers as a value which determine a positive or negative scaling.If you only define one number argument,both the X and Y axis will be scaled the same and defining both is a shorthand for X and Y.Just likerotate(),there arescaleX(),scaleY() andscaleZ()functions to scale an element on a specific axis instead.
.my-element{transform:scaleX(1.2)scaleY(1.2);}Also like therotate function, there is ascale3d() function.This is similar toscale(), but it takes three arguments: the X, Y and Z scale factor.
You can use the individualscale property to scale an element. When used outside of thetransform property, you cantransition it separately from other transformations.
Translate
Thetranslate()functions move an element while it maintains its position in the document flow.They accept length and percentage values as arguments.Thetranslate() function translates an element along the X axis if one argument is defined,and translates an element along the X and Y axis if both arguments are defined.
.my-element{transform:translatex(40px)translatey(25px);}You can—just like with other transform functions—use specific functions for a specific axis,usingtranslateX,translateY andtranslateZ.You can also usetranslate3dwhich lets you define the X, Y and Z translation in one function.
Likescale androtate, you can also use thetranslate property outside of thetransform property to move an element.
.my-element{translate:20px30px;}Skewing
You can skew an element, using theskew()functions which accept angles as arguments.Theskew() function works in a very similar way totranslate().If you only define one argument, it will only affect the X axis and if you define both,it will affect the X and Y axis.You can also useskewX andskewY to affect each axis independently.
.my-element{transform:skew(10deg);}Perspective
Lastly, you can use theperspective property—which is part of the transform family of properties—to alter the distance between the user and the Z plane.This gives the feeling of distance and can be used to create a depth of field in your designs.
This example by David Desandro, from their very useful article, shows how it can be used,along withperspective-origin-x andperspective-origin-y properties to create truly 3D experiences.
Animation functions, gradients and filters
CSS also provides functions that help youanimate elements,applygradients to them and use graphicalfilters to manipulate how they look.To keep this module as concise as possible,they are covered in the linked modules.They all follow a similar structure to the functions demonstrated in this module.
Check your understanding
Test your knowledge of functions
CSS functions can be identified by which characters?
[]{}():::CSS has built-in math functions?
Acalc() function can be placed inside of anothercalc() likefont-size: calc(10px + calc(5px * 3));
Which of the following are valid arguments forsin() andcos()?
4510deg5empiWhich of the following are CSS shape functions?
ellipse()square()circle()rect()inset()polygon()Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-06-06 UTC.