Pretty simple question. Just need to know if you can use clamp() inside of scale()? Like this:
.element {
scale(clamp(100px, 10%, 300px));
}
This does not work. How can i do this?
This
.element {
scale(clamp(100px, 10%, 300px));
}
is invalid in 2 ways. First of all there is no scale()
what you mean is transform: scale()
. Second: scale()
works with number/float only (e.g. 0.5, 1, 2). So no, clamp()
is not possible.
Edit:
What you could do is to use a css variable and media queries:
#box {
--scale: 3;
width: 64px;
height: 64px;
background-color: #aaa;
transform: scale(var(--scale));
}
@media (max-width: 768px) {
#box {
--scale: 2;
}
}
@media (max-width: 512px) {
#box {
--scale: 1;
}
}
<div id="box"></div>
Edit:
Well you could actually make the scale()
responsive by manipulating a css variable e.g. --scale
via js and using the computed font-size for clamp()
.
window.addEventListener('resize', function(event) {
scaleBox();
}, true);
window.addEventListener('load', function(event) {
scaleBox();
}, true);
function scaleBox() {
const box = document.querySelector('#box');
// Box font size in px.
const boxFontSize = parseFloat(getComputedStyle(box).fontSize);
// Document font size in px.
const documentFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
// Calculated scale factor.
const scaleFactor = boxFontSize / documentFontSize;
// Update the scale factor variable.
box.style.setProperty('--scale', scaleFactor);
console.log(`font-size: ${boxFontSize}px;`, `--scale: ${scaleFactor};`);
}
#box {
--scale: 1;
width: 64px;
height: 64px;
background-color: #aaa;
font-size: clamp(.5rem, 10vmax, 300px);
transform: scale(var(--scale));
}
<div id="box"></div>