Reputation: 69
I'm using CSS transform: scale(0.6) to scale down a div. When the element is scaled down, it maintains its aspect ratio. However, in my case, this element needs to always have a height that will reach the bottom of the viewport. This means I need to adjust the height of the element while keeping its width and top position the same.
How do I calculate the height I need to apply so that the element reaches the bottom of the viewport exactly when transform: scale(x) is applied?
below is a codesnippet. Clicking anywhere scales the div down and it's when I should apply the new height to allow the div height to reach the bottom of the viewport while keeping the same width, and position.
document.body.addEventListener('click', () => {
document.querySelectorAll('div')[0].style.transform = 'scale(0.44)';
});
body {
margin: 0;
padding: 0;
height: 100vh;
}
div {
width: 350px;
height: calc(100% - 50px);
position: absolute;
top: 50px;
background-color: red;
position: absolute;
transform-origin: top;
}
<div><h1>TEST</h1></div>
Upvotes: 1
Views: 855
Reputation: 8308
Since you want the div's height to stretch till bottom, you can make use of window.innerHeight
here.
The new height can be calculated using the following formula :-
newHeight = (viewportHeight - offsetTop)*(1/scaleValue)
Putting in values it will come down to the following calculation :-
newHeight = (window.innerHeight - div.offsetTop)*(1/0.44)
document.body.addEventListener('click', () => {
const div = document.querySelectorAll('div')[0];
div.style.transform = 'scale(0.44)';
div.style.height = `${(window.innerHeight-div.offsetTop)*(1/0.44)}px`
});
body {
margin: 0;
padding: 0;
height: 100vh;
}
div {
width: 350px;
height: calc(100% - 50px);
position: absolute;
top: 50px;
background-color: red;
position: absolute;
transform-origin: top;
}
<div>
<h1>TEST</h1>
</div>
Upvotes: 2
Reputation: 106
i see you position it from the top. i think that if you position it from bottom you will get what u want.
change top to bottom: 0px
change tranform-origin to transform-origin:bottom
and for calculating the height u could use 100VH instead of 100%
Upvotes: 0