Reputation: 69
I'm trying to change element's opacity based on how wide the browser's window is in a continuous manner. Ideally, I would like to get a unit-less value from calc
by dividing current viewport's width by some constant, like this:
opacity: clamp(0.5, calc(100vw / 1000px), 1);
but calc
doesn't allow dividing by a unit. Is there any other way to achieve this in CSS?
Upvotes: 1
Views: 685
Reputation: 1338
Unless you define some default opacities for different breakpoints using media queries I think you'd have to rely on js to achieve this. Seems like it is not possible to strip units in CSS unfortunately.
I was playing around with this in different ways and this was the closest behavior I could get:
btw you can do basic math expressions without calc function as per docs: https://developer.mozilla.org/en-US/docs/Web/CSS/clamp#parameters
var r = document.querySelector(':root');
function log() {
var width = window.innerWidth;
var opacity = getComputedStyle(document.body).opacity;
r.style.setProperty('--vp-width', width);
console.log(width, opacity);
}
window.addEventListener('resize', log);
log();
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
}
body {
opacity: clamp(0.5, var(--vp-width) / 1000, 1);
}
.content {
background: black;
height: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="content"></div>
</body>
</html>
Note: This is definitely not the best way to change opacity dynamically using js!
Upvotes: 2