W3cubDocs

/CSS

cos()

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The cos() CSS function is a trigonometric function that returns the cosine of a number, which is a value between -1 and 1. The function contains a single calculation that must resolve to either a <number> or an <angle> by interpreting the result of the argument as radians. That is, cos(45deg), cos(0.125turn), and cos(3.14159 / 4) all represent the same value, approximately 0.707.

Syntax

/* Single <angle> values */
width: calc(cos(45deg) * 100px);
width: calc(cos(0.125turn) * 100px);
width: calc(cos(0.785398163rad) * 100px);

/* Single <number> values */
width: calc(cos(63.673) * 100px);
width: calc(cos(2 * 0.125) * 100px);

/* Other values */
width: calc(cos(pi) * 100px);
width: calc(cos(e / 2) * 100px);

Parameter

The cos(angle) function accepts only one value as its parameter.

angle

A <number> or an <angle>. When specifying unitless numbers they are interpreted as a number of radians, representing an <angle>. When specifying infinity, -infinity, or NaN, the result is NaN.

Formal syntax

<cos()> = 
cos( <calc-sum> )

<calc-sum> =
<calc-product> [ [ '+' | '-' ] <calc-product> ]*

<calc-product> =
<calc-value> [ [ '*' | '/' ] <calc-value> ]*

<calc-value> =
<number> |
<dimension> |
<percentage> |
<calc-constant> |
( <calc-sum> )

<calc-constant> =
e |
pi |
infinity |
-infinity |
NaN

Example

The cos() function can be used to keep the size of a rotated box.

When the element is rotated using rotate(), it goes beyond its initial size. To fix this, we will use cos() to update the element size.

For example, if you rotate a 100px/100px square 45deg, the diamond it creates will be wider and taller than the original square. To shrink the diamond into the box allotted for the original square, you would have to scale down the diamond using this formula: width = height = 100px * cos(45deg) = 100px * 0.707 = 70.7px. You need to also adjust the transform-origin and add translate() to correct the position:

div.original-square {
  width: 100px;
  height: 100px;
  background-color: blue;
}

div.rotated-diamond {
  width: 100px;
  height: 100px;
  background-color: red;
  transform: rotate(45deg);
}

div.rotated-scaled-diamond {
  width: calc( 100px * cos(45deg) );
  height: calc( 100px * cos(45deg) );
  margin: calc( 100px / 4 * cos(45deg) );
  transform: rotate(45deg);
  transform-origin: center;
  background-color: green;
}

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
cos
No
No
103
No
No
15.4
No
No
No
No
15.4
No

See also

© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/CSS/cos