The clamp function

The clamp function takes three parameters: minimum value, preferred value, and maximum value. It returns:

Syntax

cssselector {
  property: clamp(min, pref, max);
}

Example . Limiting block size

In the following example, the preferred block size will be 30% of the screen width. But it cannot become smaller than 100px or larger than 300px:

html<div id="con1"></div>
<div id="targ"></div>
<div id="con2"></div>
css#targ {
  width: clamp(100px, 30%, 300px);
  height: 100px;
  border: 1px solid red;
  margin: 30px auto;
}
#con1 {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  margin: 30px auto;
}
#con2 {
  width: 300px;
  height: 100px;
  border: 1px solid black;
  margin: 30px auto;
}

Результат:

Example . Responsive font size

In the following example, the preferred font size will be 4vw. But it cannot become smaller than 16px or larger than 32px:

html<p id="con1">
  responsive text example
</p>
<p id="elem">
  responsive text example
</p>
<p id="con2">
  responsive text example
</p>
css#elem {
  font-size: clamp(16px, 4vw, 32px);
  color: red;
}
#con1 {
  font-size: 16px;
}
#con2 {
  font-size: 32px;
}

Результат:

Example . Responsive border radius

In the following example, the preferred border radius will be 3vw. But it cannot become smaller than 5px or larger than 20px:

html<div id="con1"></div>
<div id="elem"></div>
<div id="con2"></div>
cssdiv {
  width: 100px;
  height: 100px;
  margin: 20px auto;
  background: lightblue;
}
#elem {
  border-radius: clamp(5px, 3vw, 20px);
  background: #efafc6;
}
#con1 {
  border-radius: 5px;
}
#con2 {
  border-radius: 20px;
}

Результат:

See also

  • the min function,
    which selects the minimum value
  • the max function,
    which selects the maximum value