Open In App

CSS cos() Function

The CSS cos() function is a mathematical function that calculates the cosine of a given angle. The cosine is a trigonometric function that represents the ratio of the adjacent side to the hypotenuse of the right-angle triangle. The cosine of an angle is used to determine the x-coordinate of a point on the unit circle that corresponds to the angle.

Syntax:



width: calc(angle);

Parameters: The function accept one parameters that are described below:

Return Value: The function’s return value is the cosine of the given angle, expressed as a floating-point number between -1 and 1.



Example 1: Let’s take an example to understand how the cos() function works.




<!DOCTYPE html>
<html>
  
<head>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: green;
            position: absolute;
            top: 50px;
            left: calc(30% + 50px * cos(30deg));
        }
    </style>
</head>
  
<body>
    <h1 style="color: green;">GeeksforGeeks</h1>
    <h2>cos() function</h2>
    <div class="box">GeeksforGeeks</div>
</body>
  
</html>

Output:

 

This code will display a green box of 100×100 pixels on the screen. The position of the box will be calculated using the CSS cos() function, with a result of left: calc(30% + 50px * cos(30deg)); placing the box 50 pixels to the right of the center of the screen.

Example 2: Dynamic Width Based on the Cosine of an Angle.




<!DOCTYPE html>
<html>
  
<head>
    <style>
        .box {
            height: 100px;
            background-color: green;
            position: absolute;
            top: 50px;
            left: 30%;
            transform: translateX(-50%);
            width: calc(100px * cos(45deg));
        }
    </style>
</head>
  
<body>
    <h1 style="color: green;">GeeksforGeeks</h1>
    <h2>cos() function</h2>
    <div class="box"></div>
</body>
  
</html>

Output:

 

In this example, the width of the green box is set to be equal to its height multiplied by the cosine of 45 degrees, resulting in a value of approximately 70.7107px.

Supported browsers:


Article Tags :