CSS clamp() Method

The clamp() method in CSS allows specifying a value within a range. It takes three parameters: a minimum value, a preferred value, and a maximum value. The browser selects the preferred value if it falls within the specified range; otherwise, it chooses the minimum or maximum value.

The minimum value comes in handy when the preferred value is smaller than the minimum value similarly maximum value comes in handy when the preferred value is more than the maximum value. The preferred value becomes useful when it is between the minimum and maximum value.

The clamp() function can be used with various elements such as font-size, width, etc. Let’s built a simple layout to get a clear understanding of the clamp() function

Syntax : 

clamp(value1, value2, value3)

Parameters:

  • Here value1 represents the minimum value, value2 represents the preferred value and value3 represents the maximum value.

Example: In this example, we see how easily the width and font-size are adjusted according to viewport with the help of the clamp function. The clamp() function is very useful for typography and for creating fluid layout

html
<!DOCTYPE html>
<html>

<head>
    <style>
        /* Setting clamp property of heading */
        h1 {
            font-size: clamp(2rem, 4vw, 4rem);
            color: #eb4034;
        }

        /* Setting clamp property of box */
        .box {
            width: clamp(150px, 50%, 400px);
            height: 8rem;
            background: #5f76e8;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>Welcome To GFG</h1>
        <div class="box"></div>
    </div>
</body>

</html>

Output:

Supported Browsers:


Contact Us