The clamp function
The clamp
function takes three parameters: minimum value, preferred value, and maximum value.
It returns:
- the minimum value if the preferred value is less than the minimum
- the maximum value if the preferred value is greater than the maximum
- the preferred value if it is between the minimum and maximum
Syntax
selector {
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
:
<div id="con1"></div>
<div id="targ"></div>
<div id="con2"></div>
#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
:
<p id="con1">
responsive text example
</p>
<p id="elem">
responsive text example
</p>
<p id="con2">
responsive text example
</p>
#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
:
<div id="con1"></div>
<div id="elem"></div>
<div id="con2"></div>
div {
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;
}
: