Open In App

CSS abs() Function

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The abs() function in CSS takes a single argument, which can be a numeric value or a mathematical expression and returns the absolute value of the input, which is the distance from zero regardless of the input’s sign. One of the most common use cases for abs() is in creating responsive designs.

Syntax:  

abs(expression)

Parameters: This function only accepts a single parameter.

  • expression: It is a calculation that finally returns a number.

Return Value: It returns the absolute value of the parameter expression. 

Example 1: In this example we have used the .my-element class to set the width of the <div> element to 50% of its parent’s width minus 100 pixels, using the abs() function. It also sets a max-width of 500 pixels to ensure that the element does not grow too wide.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>CSS abs() function</title>
    <style>
        .gfg {
            --font-size: 10px;
            width: abs(var(var(--font-size)));
            max-width: 300px;
            height: 100px;
            background-color: green;
        }
  
        h3 {
            text-align: center;
            color: #fff;
        }
    </style>
</head>
  
<body>
    <div class="gfg">
        <h3>GFG</h3>
    </div>
</body>
  
</html>


Output:

 

Example 2: This example demonstrates how abs() can be used to center an element horizontally within its parent element.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Centering an element with abs() function
    </title>
      
    <style>
        .parent {
            width: 400px;
            height: 300px;
            background-color: gray;
            display: flex;
            justify-content: center;
            align-items: center;
        }
  
        .child {
            width: 150px;
            height: 150px;
            background-color: red;
            margin-left: abs((100% - 150px) / 2);
        }
    </style>
</head>
  
<body>
    <div class="parent">
        <div class="child"></div>
    </div>
</body>
  
</html>


Output:

 

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/abs

Supported browsers: The browsers supported by the abs() function are listed below:

  • Safari 15.4
  • Safari on iOS


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads